【问题标题】:Can't save data from collection_select helper to model无法将 collection_select 助手中的数据保存到模型
【发布时间】:2017-12-12 19:37:26
【问题描述】:

我正在尝试使用 collection_select 帮助器通过表单将组织保存到联系人模型,但它没有将数据保存到模型中。我似乎无法理解为什么。

我正在使用 Rails 5.1.4

这是我的 contact.rb 模型:

class Contact < ApplicationRecord
belongs_to :organization
has_many :deals
end

这是我的 organization.rb 模型:

class Organization < ApplicationRecord
has_many :deals, through: :contacts
has_many :contacts, dependent: :destroy
end

这是我的 schema.rb

create_table "contacts", force: :cascade do |t|
t.string "contact_name"
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["organization_id"], name: 
"index_contacts_on_organization_id"
end

create_table "organizations", force: :cascade do |t|
t.string "org_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

这是我的 contacts_controller.rb

def new
@contact = Contact.new
end

def edit
@contact = Contact.find(params[:id])
end

def create
@contact = Contact.new(contact_params)

if @contact.save
redirect_to @contact
else
render 'new'
end
end

private

def contact_params
params.require(:contact).permit(:contact_name, :organization_id,
                                organizations_attributes: [:org_name, 
:id])
end 

这是我的 new.html.erb 文件:

<h1>New Contact</h1>

<%= form_with scope: :contact, url: contacts_path, local: true do |form| %>

<p>
<%= form.label :contact_name %><br>
<%= form.text_field :contact_name %>
</p>

<p>
<%= form.label :organization %><br>
<%= form.collection_select(:organization_id, Organization.all, :id, :org_name) %>
</p>

<p>
<%= form.submit %>
</p>
<% end %>
<hr>

编辑:我为我的控制器和架构添加了参数。

【问题讨论】:

  • 请在提交表单时发布正在发送的参数

标签: ruby-on-rails ruby ruby-on-rails-5


【解决方案1】:

在 organization.rb 模型中:

class Organization < ApplicationRecord
  has_many :deals, through: :contacts
  has_many :contacts, dependent: :destroy

  def org_name
    "#{name}"
  end
end

在你的 new.html.erb 文件中:

<%= form.fields_for :organizations do |o| %>
  <%= o.collection_select(:organization_id, Organization.all,
                          :id, :org_name,
                          {:prompt => 'Please select the organization'}) %>

【讨论】:

  • 好吧,我尝试制作一个嵌套表单,但我收到一条错误消息,上面写着undefined method build' for nil:NilClass`,所以我一定是做错了什么。
  • 请提供org_name 或在使用嵌套表单后更新您的视图
猜你喜欢
  • 1970-01-01
  • 2021-01-25
  • 2011-02-27
  • 2012-12-18
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
  • 2017-10-11
相关资源
最近更新 更多