Ruby on Rails Wednesday, April 24, 2013

On 24 April 2013 09:19, Paul Ols <lists@ruby-forum.com> wrote:
> Hi!
>
> I have a User model that has_and_belongs_to_many Awards.
> The awards table is pre-populated, and there's an awards_users join
> table.
>
> In a rails console, If I do:
> u = User.find(1)
> u.awards.build(award_id: 1)
>
> the award model that is built is an actual Award model, not an
> AwardsUser model, like I would expect.
> so, If i try to save the user model it violates the primary key index
> because it is also trying to save a new Award, with the id 1.
> I was expecting this to create a new row in the awards_users table
> instead, with the user_id and award_id of 1.
>
> Any ideas where I've gone wrong?

You should not try and set the id manually, let Rails take care of that.
award = u.awards.build
should build an award object, then award.save should save it.

Having said that I much prefer to use has_many through and manage the
join table myself. I find it easier to follow what is happening.

Colin

>
> --
> Posted via http://www.ruby-forum.com/.
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment