accepted_nested_attributes_for通过连接表与连接和现有记录上的属性

时间:2018-04-06 12:48:13

标签: ruby-on-rails nested-forms nested-attributes strong-parameters

现有公司和方向(风景,肖像),必须为公司创建app_accesses(STI类型:iPhone,iPad,桌面)。 该视图是app_accesses类型的下拉列表和方向复选框,要求是为选定类型和方向选中的公司保存app_accesses

因此,对于单个公司的单个AppAccess类型和多个orientation_id,应该保存连接表

模特

  class Company < ApplicationRecord
    has_many :app_accesses
    has_many :orientations, through: :app_accesses
    accepts_nested_attributes_for :app_accesses
  end

  class Orientation < ApplicationRecord
    has_many :app_accesses
    has_many :companies, through: :app_accesses
  end

  class AppAccess < ApplicationRecord
    belongs_to :company
    belongs_to :orientation
    accepts_nested_attributes_for :orientation
  end

控制器看起来像

class CompaniesController < ApplicationController
  before_action :find_company, only: [:show, :edit, :update, a_access_new, :a_access_create]
  def new
    @company = Company.new
  end

  def create
    @company = Company.new(company_params)
    @company.save  
  end

  def a_access_new
    @com_acc = Company.find(params[:id])
    @com_acc.app_accesses.build.build_orientation
  end

  def a_access_create
    //save attributes here    
  end
end

视图看起来像

= form_for @com_acc, url: a_access_create_company_path(@com_acc), :method => :POST , local: true do |f|
  = f.fields_for :app_accesses do |app|
    .row
      - devices = ['Iphone', 'Ipad', 'Desktop']
      = app.label :type, 'Device Type:', class: "col-lg-3 control-label"
      .col-lg-9
        = app.collection_select :type, devices, :to_s, :to_s, class: 'form-control custom-checkbox'
      = app.fields_for :orientation do |orient|
        = orient.collection_check_boxes(:id, Orientation.all, :id, :name, include_hidden: false) do |b|
          = b.check_box
          = b.label
    .row
      = f.submit 'Save'

强参数如何?我面临参数问题而且没有被保存。

保存时还会收到accepts_nested_attributes_for to link to existing record, not create a new one之类的错误

0 个答案:

没有答案