Rails has_and_belongs_to_many relationship question

Posted by Kevin Whitaker on Stack Overflow See other posts from Stack Overflow or by Kevin Whitaker
Published on 2010-04-29T19:10:12Z Indexed on 2010/04/29 19:37 UTC
Read the original article Hit count: 505

Filed under:
|
|

Hello all,

I'm sure that this question has been asked somewhere before, as the habtm relationship seems to be very confusing.

I have two models, users and promotions. The idea is that a promotion can have many users, and a user can have many promotions.

class User < ActiveRecord::Base
  has_and_belongs_to_many :promotions
end

class Promotion < ActiveRecord::Base
  has_and_belongs_to_many :users
end

I also have a promotions_users table/model, with no id of its own. It references user_id and promotions_id

class PromotionsUsers < ActiveRecord::Base
end

So, how do I add a user to a promotion? I've tried something like this:

user = User.find(params[:id])
promotion = Promotion.find(params[:promo_id])
promo = user.promotions.new(promo)

This results in the following error:

NoMethodError: undefined method `stringify_keys!' for #<Promotion:0x10514d420>

If I try this line instead: promo= user.promotions.new(promo.id)

I get this error:

TypeError: can't dup Fixnum

I'm sure that there is a very easy solution to my problem, and I'm just not searching for the solution the right way.

Thank you for your time, and any help you can provide.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about relationship