【问题标题】:Rails nested attributes for many to many多对多的 Rails 嵌套属性
【发布时间】:2016-09-27 09:33:40
【问题描述】:

您好,我正在尝试使用嵌套属性来实现一项功能。在创建让分盘(针对客户)的表单中,我想显示所有客户联赛的列表,当在创建操作中提交表单时,我会使用@handicap.save,这将创建让分盘之间的关联以及联赛(表格中选择的联赛)。

我找到的唯一解决方案是不使用嵌套属性。 在新方法中,我会从客户那里获得所有障碍并在表格中显示它们。因此,当在创建操作中提交表单时,我会进行验证..,为客户创建 @handicap 记录,然后 手动为来自我将创建关联的表单的每个 League Id。

#New/Create actions in the handicaps controller

def new
  @leagues = @customer.leagues
end

def create
  handicap = @customer.handicaps.build(handicap_params)
  if handicap.save
    associations = []
    params[:league_ids].each do |id|
      associations << LeagueHandicap.new(handicap_id: @handicap.id, league_id: id)
    end
    LeagueHandicap.import(associations)
  end
end

我也想做 handicap.save 并自动创建 LeagueHandicap 关联。但是我不知道如何使用嵌套属性来做到这一点。可以这样吗?

我有以下型号:

class Customer < ActiveRecord::Base
  has_many :handicaps, dependent: :destroy
  has_many :leagues, dependent: :destroy
end

class Handicap < ActiveRecord::Base
  belongs_to :customer
  has_many :league_handicaps
  has_many :leagues, through: :league_handicaps, dependent: :destroy
end

class LeagueHandicap < ActiveRecord::Base
  belongs_to :handicap
  belongs_to :league
end

class League < ActiveRecord::Base
  has_many :league_handicaps
  has_many :handicaps, through: :league_handicaps, dependent: :destroy
end

(通过 LeagueHandicap 在让分盘和联赛之间建立多对多关系)

【问题讨论】:

    标签: ruby-on-rails ruby forms ruby-on-rails-4 nested-attributes


    【解决方案1】:

    如果您允许 league_ids rails 应该为您添加它们。你需要告诉 rails 它是一个数组

    def handicap_params
      params.require(:handicap).permit(league_ids: [])
    end
    

    【讨论】:

    • 我怎样才能在表格中显示客户@leagues。因此,当表单是提交者时,我会得到如下内容:{handicap: {info_about handicap: {}, League_ids: [1, 2, 3] }}。我发现很难在视图中正确显示联赛。我需要使用总和,例如:f.fields for :leagues do |builder| ?
    • 类似collection_check_boxes f.collection_check_boxes(league_ids, League.all, :id, :name)
    • 很好用!但是我们不能使用相同的方法进行编辑,对吗?如果我们使用collection_check_boxes,即使我们更改了更新方法rails中的检查,也不会删除最后一个关联并创建新的关联。有没有办法让 Rails 也这样做,这样我们就不需要硬编码了?
    • 可以,rails 会根据需要添加和删除关联
    • 成功了,非常感谢!这个原则是基于多对多的关联?想知道我可以从哪里获得更多关于重要小事的知识?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多