我尝试使用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>
编辑:我为我的控制器和架构添加了参数。
答案 0 :(得分:0)
在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'}) %>