Add record to a has_and_belongs_to_many relationship

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.

Answers


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

user.promotions is an array of the promotions tied to the user.

See the apidock for all the different functions you have available.


You can do just

User.promotions = promotion #notice that this will delete any existing promotions

or

User.promotions << promotion

You can read about has_and_belongs_to_many relationship here.


This is also useful

User.promotion.build(attr = {})

so, promotion object saves, when you save User object.

And this is

User.promotion.create(attr = {})

create promotion you not need to save it or User model


Need Your Help

Pycharm and unittest does not work

python pycharm python-unittest

I have a problem with PYCharm 3.0.1 I can't run basic unittests.

Constructing an Abstract Syntax Tree with a list of Tokens

java interpreter abstract-syntax-tree

I want to construct an AST from a list of tokens. I'm making a scripting language and I've already done the lexical analysis part, but I have no idea how to create an AST. So the question is, how d...