将记录添加到has_and_belongs_to_many关系中

问题描述 投票:25回答:4

我有两种模式,用户和促销。这个想法是,促销可以有很多用户,而一个用户可以有很多促销。

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

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 #<Promotion:0x10514d420>

如果我改为尝试以下行:promo = user.promotions.new(promo.id)

我收到此错误:

TypeError: can't dup Fixnum

我确信对我的问题有一个非常简单的解决方案,而我只是没有以正确的方式寻找解决方案。

ruby-on-rails has-and-belongs-to-many relationship
4个回答
48
投票
user = User.find(params[:id])
promotion = Promotion.find(params[:promo_id])
user.promotions << promotion

user.promotions是与用户绑定的促销数组。

请参阅apidock以获取所有可用的不同功能。


10
投票

您可以做

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

User.promotions << promotion

您可以阅读有关has_and_belongs_to_many关系here


9
投票

这也很有用

User.promotion.build(attr = {})

因此,保存促销对象时,将保存用户对象。

这是

User.promotion.create(attr = {})

无需创建促销或用户模型即可创建促销


0
投票

如果您想使用原型的PromotionsController CRUD设置将用户添加到促销中,并且不是使用Rails表单助手,则可以将参数的格式设置为:

params = {id: 1, promotion: { id: 1, user_ids: [2] }}

这可以使控制器保持苗条,例如,您不必为update方法添加任何特殊内容。

class PromotionsController < ApplicationController

  def update
    promotion.update(promotion_params)

    # simplified error handling
    if promotion.errors.none?
      render json: {message: 'Success'}, status: :ok
    else
      render json: post.errors.full_messages, status: :bad_request
    end
  end

  private

  def promotions_params
    params.require(:promotion).permit!
  end

  def promotion
    @promotion ||= Promotion.find(params[:id])
  end
end

结果将是:

irb(main)> Promotion.find(1).users
=> #<ActiveRecord::Associations::CollectionProxy [#<User id: 2 ...>]>
© www.soinside.com 2019 - 2024. All rights reserved.