问题描述
我有两种模式,用户和促销.这个想法是,促销可以有很多用户,而一个用户可以有很多促销.
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
我也有一个Promotions_users表/模型,没有自己的ID.它引用了user_id和Promotions_id
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)
这将导致以下错误:
NoMethodError: undefined method `stringify_keys!' for #<Promotion:0x10514d420>
如果我改用这一行:promo = user.promotions.new(promo.id)
If I try this line instead:promo= user.promotions.new(promo.id)
我收到此错误:
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.
推荐答案
user = User.find(params[:id])
promotion = Promotion.find(params[:promo_id])
user.promotions << promotion
user.promotions
是与用户相关联的促销的数组.
user.promotions
is an array of the promotions tied to the user.
有关可用的所有不同功能,请参见 apidock .
See the apidock for all the different functions you have available.
这篇关于将记录添加到has_and_belongs_to_many关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!