开发者

Nested form to invoke custom factory method instead of new()

This problem is related to this question: Hashing an IP for saving

I have a model called Post. I have to pass in the IP address during post creation. I was told not to override the initialize(). So I used a factory method as suggested here: how to override new method for a rails model:

#Post.rb model
def self.new_with_ip(ip, attributes={})
  self.new(attributes['one_day_id'] = do_some_conversion_on(ip))
end

However this does not get invoked, because Post is nested within a Discussion, and the nested form will not call this factory method. How can I make the form to in开发者_JS百科voke this instead of the traditional Post.new()?


If this is being passed through as a nested attribute of a form then you would have to override the posts_attributes= method of the Discussion model:

def posts_attributes=(attribute_sets)
  attribute_sets.each do |attributes|
    Post.new_with_ip(ip_goes_here, attributes)
  end
end

Of course you're going to need to modify that a little if you're going to be getting nested posts in an update kind of fashion, as you'll want to update existing posts rather than creating new ones. Sounds like a good exercise in learning :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜