开发者

What is a better way to create STI model instance

Normally one would build a related model instance through its parent object:

@child = @parent.children.build(params[:child])

But when we're using STI and we want to do this while at the same time building it as one of the subclasses the syntax seems to break down. This is the best way to do it as far as I can tell (ignore the security problems around not checking the type against an approved list):

@child = params[:type].classify.constantize.new(params[params[:type]])
@child.parent = @parent

Is this the best way to go about it? I'm using a single controller to build all the different subclass types so I need to supply th开发者_运维百科e type as a parameter.


I usually use this trick:

class BaseModel < ActiveRecord::Base

private
  # this will enable you to set the type field 
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end

Now in your controller:

@parent.children.build(params[:base_model])

Make sure params[:base_model] hash has a field called type. I usually add a hidden form field to store the type.

Make sure you add the relevant checks to ensure the correct sub types are created.

Note : This trick will not work in Rails 3.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜