Nested attributes with required protected attributes

Hi,

I've got 3 models: Comment, Venue and User. Comment has many :venues
and belongs to :user. Venue belongs to :user as well.

When adding a comment, user should be able to attach a venue to it.

In Venue model "user_id" attribute is protected and it is required as
well - this causes problem when trying to create a venue when adding a
comment using nested attributes, because I can't pass "user_id"
attribute required by venue - it's protected and thus rejected.

Any ideas how to solve it?

Hi Szimek,

You can do it like this:

hash to simulate what comes from your params[:comment]

comment = { :text => “Comment text”, :venues_attributes => [{ :name => “one” }, { :name => “two” }] }

you set the user id by calling a block on create

Comment.create(model) { |c| c.venues.each { |v| v.user_id = 1 } }

Hope this helps.

/Lasse

Whoops,

Comment.create(model)

should of course be

Comment.create(comment)

And you should be able to replace it with

Comment.create(params[:comment])

/Lasse