class Member < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts
end
params = { :member => {
:name => 'joe', :posts_attributes => [
{ :title => 'Kari, the awesome Ruby documentation browser!' },
{ :title => 'The egalitarian assumption of the modern citizen' },
]
}}
member = Member.create(params['member'])
After doing this I want is to map the elements in posts_attributes in params hash to th开发者_如何学编程e id's (The primary keys) after they are saved. Is there any thing I can do when accepts_nested_attributes_for builds or creates each record
PS: posts_attributes array may not contain index in sequence I mean this array might not contain index like 0,1,2 it can contain index like 0,127653,7863487 as I am dynamically creating form elements through javascript
also, I want is to associate only new records created in Post and not already existing Post
Thanks in Advance
Have you considered refreshing the posts
association and grabbing the posts_attributes
array in full?
Unfortunately, there is not a reliable way to do what you want. You could try looping over both and finding the IDs associated with the content using string matching, but without a field on the posts that is guaranteed to be a unique value, there's not an effective way to do it.
Although I'm not quite sure about what elements you want to assign with what ids, I think this approach would give you a hint.
You may assign a method name symbol to :reject_if
, then put your logic into that method, like this:
class Member < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts, :reject_if => :reject_posts?
def reject_posts?(attrs)
# You can do some assignment here
return true if attrs["title"].blank?
post_exist = self.posts.detect do |p|
p.title == attrs["title"]
end
return post_exist
end
end
精彩评论