【问题标题】:Accepting *singular* parameters with has_many through association通过关联接受带有 has_many 的 *singular* 参数
【发布时间】:2014-07-22 22:35:25
【问题描述】:

我有一组如下所示的 Rails 模型,并在 Rails 4 中使用强大的参数通过钱包模型创建卡和用户之间的关联:

class User < ActiveRecord::Base
  has_many :wallets
  has_many :cards, through: :wallets
end

class Card < ActiveRecord::Base
  has_many :wallets
  has_many :users, through: :wallets
end

class Wallet < ActiveRecord::Base
  belongs_to :user
  belongs_to :card
end

在我的基础卡控制器中,我定义了如下强参数:

def card_params
  params.require(:card).permit(:nickname, :number, :user_ids)
end

但在我的 API 卡控制器中,我想接受一个单一的 user_id 作为“user_id”键的值。如何设置 API::CardsController 类以通过 POST 接受 user_id 而不是(或除此之外) user_ids?

我的 API 卡控制器的要点:https://gist.github.com/tfilter/91986ae0ed6e215cbeca

【问题讨论】:

    标签: ruby-on-rails-4 associations rails-activerecord


    【解决方案1】:

    首先想到的是将:user_id 添加到您的permit 调用中,然后将其分配给像card.user_ids = [card_params[:user_id]] 这样的user_ids。

    您可以做的第二件事是直接在card_params 方法中分配它。像这样的。

    def card_params
      cp = params.require(:card).permit(:nickname, :number, :user_ids)
      cp[:user_ids] = [params[:card][:user_id]] if params[:card][:user_id]
      cp
    end
    

    如果我想出更优雅的方法,我会更新答案。

    【讨论】:

    • 看起来不错——我最终在我的 API 和基本控制器中都采用了第二种方法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多