开发者

Ignore 'read-only' column in creates and updates in Ruby ActiveRecord

I'm looking for a solution to the following problem: I have an ActiveRecord entity that is backed by an updatable database view (in DB2 via the activerecord-jdbc-adapter gem). This view contains one column that is calculated from other columns and is 'read-only': you cannot set that column in any valid way. When a new record is created for this entity, that field should 开发者_StackOverflow社区not be set. However, by default, ActiveRecord does set it with the 'default' (NULL), which is rejected by the database.

attr_readonly isn't a solution, because that only excludes a column from updates and not from creates.

attr_ignore, such as implemented by the 'lincoln' gem, is not a solution either, because then the field is ignored entirely. However, the column still needs to be read and be accessible. It's actually even used as part of a relation.

There are ways to prevent you from setting a certain attribute of an ActiveRecord entity, but that doesn't usually prevent that attribute from being included in create or update statements

Does anyone know if there is a way in ActiveRecord to specify a column as 'never set this field'?

Update, in response to Arsen7: I've attempted to use the after_initialize hook to remove the attribute from a newly created entity, so it isn't included in the SQL that is built. The trouble with this is that the attribute is completely removed and not available anymore at all, pretty much identical to the 'igonre_attr' situation described above. Due to caching, that's not trivial to get around and would require additional logic to force a reload of entities of these specific tables. That can probably be achieved by overriding create to add a 'reload', in addition to using the after_initialize.

(As pointed out by Arsen7, I forgot to mention I'm at ActiveRecord 3.0.9)

My solution

Since my entities already inherit from a subclass of ActiveRecord::Base, I've opted to add before_create and after_create hooks. In the before_create hook, I remove the 'calculated' columns from the @attributes of the instance. In the after_create hook, I add them again and read the values of the 'calculated' columns from the database to set them to the values they received.

Adding such hooks is almost identical to overriding create, so I consider Arsen7's answer to be correct.


I'm afraid ActiveRecord is not prepared for the use case you need. (By the way: which version of AR are you using?)

But I believe you may apply two possible workarounds.

The first, is to overwrite the 'create' method of your model, executing some other SQL, prepared manually in the worst case. I suppose that the real function which will need to be overwritten will not be the 'create' itself, but looking at the sources you could find the one.

The other solution, and I believe, a more elegant one, would be to create a trigger in the database. I am more in the PostgreSQL world, where I would use a 'CREATE RULE', but looking at the DB2 documentation I see that in DB2 there are 'INSTEAD OF' triggers. I hope this may be helpful.


I have achieved the same result by overriding ActiveRecord::Base#arel_attributes in my model:

Class Model < ActiveRecord::Base
  @@skip_attrs = [:attr1, :attr2]     

  def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
    skip_attrs = @@skip_attrs.map { |attr| [self.class.arel_table[attr] }
    attrs = super(include_primary_key, include_readonly_attributes, attribute_names)
    attrs.delete_if {|key, value| skip_attrs.include?(key) }         
  end 
end

The attributes in the @@skip_attrs array will be ignored by ActiveRecord on both insert and update statements, as they both rely on arel_attributes_values for returning the list of attributes of the model.

A better solution would be: a patch on ActiveRecord::Base#arel_attributes along with a 'attr_ignore' macro similar to 'attr_readonly'.

cheers


I know this is very old, but I have been struggling with this very same issue. I have a database with a trigger that calculates an index value based on the max value within a key. I, too, want to prevent any ability to set the value in AR as it could throw off the index applied as rows are inserted.

CREATE TRIGGER incr_col_idx
AFTER INSERT ON fl_format_columns
FOR EACH ROW
BEGIN UPDATE fl_format_columns
SET idx = (SELECT coalesce(max(idx),-1) + 1
           FROM fl_format_columns
           WHERE fl_file_format_id = new.fl_file_format_id)
WHERE fl_file_format_id = new.fl_file_format_id AND name = new.name;
END;

I've tried a variety of things, but it always came back to overriding the setter directly.

# @raise ArgumentError when an attempt is made to set a value that is calculated in db
def idx=(o)
  raise ArgumentError,'the value of idx is set by the db. attempts to set value is not allowed.' unless o.nil?
end

This will require catching the exception rather than interrogating the errors array, but that is what I ended up with. It does pass the following inspection:

context 'column index' do
  it 'should prevent idx from being set' do
    expect{FL_Format_Column.create(fl_file_format_id:-1,name:'test idx',idx:0)}.to raise_error(ArgumentError)
  end
  it 'should calculate idx relative to zero' do
    x = FL_Format_Column.create(fl_file_format_id:-1,name:'test_idx_nil')
    expect(x.errors[:idx].any?).to be false
    expect(FL_Format_Column.last.idx).to be > -1
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜