将记录添加到has_and_belongs_to_many关系中
我有两个模型,用户和促销活动。 这个想法是促销可以有很多用户,用户可以有很多促销。
class User < ActiveRecord::Base has_and_belongs_to_many :promotions end class Promotion < ActiveRecord::Base has_and_belongs_to_many :users end
我还有一个promotion_users表/模型,没有自己的id。 它引用了user_id和promotions_id
class PromotionsUsers < ActiveRecord::Base end
那么,如何将用户添加到促销中? 我尝试过这样的事情:
user = User.find(params[:id]) promotion = Promotion.find(params[:promo_id]) promo = user.promotions.new(promo)
这会导致以下错误:
NoMethodError: undefined method `stringify_keys!' for #
如果我改为尝试这一行:promo = user.promotions.new(promo.id)
我收到此错误:
TypeError: can't dup Fixnum
我确信我的问题有一个非常简单的解决方案,而我只是没有以正确的方式寻找解决方案。
user = User.find(params[:id]) promotion = Promotion.find(params[:promo_id]) user.promotions << promotion
user.promotions
是与用户相关的促销数组。
有关您可用的所有不同function,请参阅apidock 。
你可以做到
User.promotions = promotion #notice that this will delete any existing promotions
要么
User.promotions << promotion
你可以在这里阅读关于has_and_belongs_to_many
关系。
这也很有用
User.promotion.build(attr = {})
因此,当您保存用户对象时,促销对象会保存。
这是
User.promotion.create(attr = {})
创建促销您不需要保存它或用户模型