Associate nested attributes with identifiers that they get after saving

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 that, I want them to display the elements in posts_attributes in hash parameters with identifier (primary keys) after saving them. Is there anything I can do when accepts_nested_attributes_for creates or creates each record.

PS: posts_attributes array may not contain an index in the sequence I mean that this array may not contain an index such as 0,1,2, it may contain an index such as 0,127653,7863487 as I dynamically create form elements through javascript

In addition, I want to link only new posts created in Post and no longer existing Post

Thanks at Advance

+3
source share
2

posts posts_attributes ?

, , . , , , , , .

+1

, , , .

:reject_if, , :

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
0

Source: https://habr.com/ru/post/1780458/


All Articles