Trantor Liu
Trantor Liu

Reputation: 9126

Rails accepts_nested_attributes_for creating only

I have a Post model. I would like to let users create post comments while creating/updating a post by accepts_nested_attributes_for :comments. However, I don't want to let users update comments by nested attributes.

Is there a way to do something like accepts_nested_attributes_for :comments, create_only: true?

Upvotes: 6

Views: 1506

Answers (2)

Mohamed Hamed
Mohamed Hamed

Reputation: 91

You can reject_if the id attribute is present:

accepts_nested_attributes_for :comments, reject_if: proc { |attributes| attributes['id'].present? }

Upvotes: 0

afilipko
afilipko

Reputation: 81

Try to use something like this accepts_nested_attributes_for :comments, reject: :persisted? This will check, if Post object persisted or not. You also can replace persisted? with your custom method

Upvotes: 3

Related Questions