1

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 invoke this instead of the traditional Post.new()?

Community
  • 1
  • 1
lulalala
  • 17,572
  • 15
  • 110
  • 169

1 Answers1

2

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 :)

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • thanks. Does it mean that I have to add a factory method to the Discussion in order to pass IP address from the controller? – lulalala Aug 11 '11 at 07:00
  • @lulalala: You could set `ip` as a virtual attribute (using `attr_accessor`) on your `Discussion` model and set it as you pass through the parameters from the controller. – Ryan Bigg Aug 11 '11 at 07:25