简体   繁体   English

Rails嵌套了许多属性

[英]Rails nested attributes for many to many

Hi I am trying to implement a feature using nested attributes. 嗨,我正在尝试使用嵌套属性来实现功能。 In the form for creating a handicap (for Customer) I would like to display a list of all the Customer's leagues and when the form is submitted in the Create action, I would use @handicap.save and this will create the association between the Handicap and Leagues as well (the leagues that were selected in the form). 在创建让分盘(针对客户)的表单中,我想显示所有客户联赛的列表,当在Create操作中提交表单时,我将使用@ handicap.save,这将在让分盘之间建立关联和联赛(在表格中选择的联赛)。

The only solution I found was without using nested attributes. 我发现的唯一解决方案是不使用嵌套属性。 In the new method I would get all the handicaps from customer and display them in the form. 在新方法中,我将从客户那里获得所有障碍,并以表格形式显示。 So when the form is submitted in the create action I would do validations.., create the @handicap record for Customer and then manually for each League Id that comes from the form I would create the associations. 因此,当在create操作中提交表单时,我将进行验证..,为Customer创建@handicap记录,然后手动为来自表单的每个联赛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

I would want to do handicap.save and automatically create the LeagueHandicap associations as well. 我想做handicap.save并自动创建LeagueHandicap关联。 However I have no clue on how to do it with nested attributes. 但是,我不知道如何使用嵌套属性。 Can it be done like this? 可以这样吗?

I have the following models: 我有以下型号:

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

(Many to many relationships between Handicap and League through LeagueHandicap) (通过LeagueHandicap,障碍和联赛之间有许多关系)

If you permit league_ids rails should add them for you. 如果允许的league_ids rails应该为您添加它们。 You need to tell rails it's an array though 您需要告诉rails它是一个数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM