首页 > 解决方案 > 如何使用集合选择为嵌套属性设置表单?

问题描述

我正在尝试使用 RoR 上的选择器为嵌套属性配置表单,但似乎我做错了。

我正在尝试affaire使用 nested_attributes创建一个新的contributions。每个都contribution属于skill需要定义的一个。

由于可能的数量有限skills,我想在我的表单中有一个选择器来contribution_skill从列表中选择。

编辑:我终于通过设置所有contribution属性来保存事务(我在模型定义中使用了默认设置)。但我并不总是希望定义这些属性,所以它仍然不是解决方案。我补充说,这些属性没有存在验证。任何人都知道如何保存nested_attribute没有所有nested_attribute_attributes定义的?

这是模型定义:

class Affaire < ApplicationRecord
  has_many :contributions
  accepts_nested_attributes_for :contributions
end


class Skill < ApplicationRecord
  has_many :contributions
end

class Contribution < ApplicationRecord
  belongs_to :skill
  belongs_to :affaire
end

控制器定义:

def new
    @affaire = Affaire.new
    2.times {@affaire.contributions.build}
end

def create
    @affaire = Affaire.new(affaire_params)
    @affaire.save
    redirect_to @affaire
end

private
    def affaire_params
      params.require(:affaire).
        permit(:nam, contributions_attributes: [:id, :skill_id])
    end

查看定义:

<%= form_with model: @affaire do |form| %>
    <%= form.label :name, "Name of Affaire" %>
    <%= form.text_field :name %>

    <%= form.fields_for :contributions do |ff| %>
        <%= ff.label :skill_id, "Contribution" %>
        <%= ff.collection_select(:skill_id, Skill.all, :id, :name) %>
    <% end %>

<%= form.submit "Create affaire" %>

我期待着用我的和它的集合来affaire创建我的。不幸的是,它出错了。contributioncontributionskill

这是我在rails server控制台中得到的:

Started GET "/affaires/new" for ::1 at 2019-09-04 21:06:41 +0200
Processing by AffairesController#new as HTML
  Rendering affaires/new.html.erb within layouts/application
  Skill Load (0.4ms)  SELECT "skills".* FROM "skills"
  ↳ app/views/affaires/new.html.erb:30
  CACHE Skill Load (0.0ms)  SELECT "skills".* FROM "skills"
  ↳ app/views/affaires/new.html.erb:30
  Rendered affaires/new.html.erb within layouts/application (20.9ms)
Completed 200 OK in 105ms (Views: 70.3ms | ActiveRecord: 2.2ms)


Started POST "/affaires" for ::1 at 2019-09-04 21:06:48 +0200
Processing by AffairesController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"GCc2wX2C7mWn77eksjdhDp5i1lFoUc2L3MLkOIXmWhavNdxwIynpNTVaRmbrvkKNdRtQxqoXjaInI2MaJtvvFA==", "affaire"=>{"name"=>"test",  "contributions_attributes"=>{"0"=>{"skill_id"=>"3"}, "1"=>{"skill_id"=>"1"}}}} (0.3ms)  BEGIN
  ↳ app/controllers/affaires_controller.rb:20
  Skill Load (0.3ms)  SELECT  "skills".* FROM "skills" WHERE "skills"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
  ↳ app/controllers/affaires_controller.rb:20
  Skill Load (0.3ms)  SELECT  "skills".* FROM "skills" WHERE "skills"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/affaires_controller.rb:20
   (0.2ms)  ROLLBACK
  ↳ app/controllers/affaires_controller.rb:20
Redirected to http://localhost:3000/affaires
Completed 200 OK in 27ms (ActiveRecord: 2.8ms)

我看不出问题出在哪里。如果我参考 Rails 文档,参数对我来说似乎没问题。我不明白为什么它会回滚。

谢谢你的帮助

标签: ruby-on-railsformsnested-attributescollection-select

解决方案


推荐阅读