0

I am working with nested attributes and strong params and I’ve seen two different ways of nesting attributes in strong params.

Take this example:

class Post < ActiveRecord::Base
has_many :comments
accepts_nested_attributes, :comments

class Comments < ActiveRecord::Base
belongs_to :post

I have seen these two ways of nesting params for comments in the Post Controller, is there a difference?

params.require(:post)
      .permit(:title, :id, :author, :comment => [:id, :content, :post_id, :user_id])

or

params.require(:post)
      .permit(:title, :id, :author, comments_attributes: [:id, :content, :post_id, :user_id])


They look similar...normally I would think that one was an earlier version, but I believe strong params is relatively new. What is the difference?

NothingToSeeHere
  • 2,253
  • 5
  • 25
  • 57
  • Never seen them used like that. The second one is what it should be. Do they both work? – DickieBoy Mar 19 '15 at 18:12
  • I have only used the second one successfully. I was provided with code here at so that used the first one and the code didn't work. I am too new to see if the difference was related to the params, my ignorance, or the new code. Also, this answer uses the first one...though it may not actually be nested_attributes: http://stackoverflow.com/questions/18436741/rails-4-strong-parameters-nested-objects?rq=1 – NothingToSeeHere Mar 19 '15 at 18:14

1 Answers1

1

Just two different hash syntaxes in Ruby

params.require(:post).permit(:title, :id, :author, :comments_attributes => [:id, :content, :post_id, :user_id])

and

params.require(:post).permit(:title, :id, :author, comments_attributes: [:id, :content, :post_id, :user_id])

are the same

When you add the accepts_nested_attributes_for :comments, it creates a comments_attributes method. The comments method will expect an array, not sure what it would do if you sent it a comments param, maybe nothing. The link to the other 'nested params' example is not the same as accepts_nested_attributes.

Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70
  • Thank you! Is one of them preferred? I seem to see the second more often and it looks a little more Rails 4 to me. – NothingToSeeHere Mar 19 '15 at 18:36
  • 1
    The second one. The first approach is not a special convention, it just a way to pass a hash to a method in the model (in this case, the method is `comment=(hash)`. You can pass anything through params and have the server process it. In the link to the example, they are just sending json which is parsed and processed on the server, calling a bunch of setters. If you actually want nested_attributes and all that comes with that, it's always the 'obj_attributes' convention. – Mark Swardstrom Mar 19 '15 at 18:43