[英]Rails: belongs_to association through a form not populating
我正在為我的班級Project
控制器。 它與Client
之間有一個belongs_to
關系。
我不確定為什么會這樣,但是當我通過表單創建一個新項目時,會為其分配一個name
,但是沒有fee
,也沒有client_id
。
以下是相關代碼:
項目負責人
class ProjectsController < ApplicationController
def index
end
def show
end
def new
@project = Project.new
end
def edit
end
def create
@project = Project.new(project_params)
if @project.save
redirect_to projects_url
else
render 'new'
end
end
def update
end
def destroy
end
private
def project_params
params.require(:project).permit(:name, :feee, :client_id)
end
end
項目/新視圖
<div id="newproject-form">
<h1>Create a project</h1>
<%= form_for @project do |p| %>
<div id="newproject-form-input">
<ul>
<li><%= p.label :name, "Project name: " %><br>
<%= p.text_field :name, size: 40 %></li>
<li><%= p.label :fee, "Fee: " %><br>
<%= p.text_field :fee %></li>
<li><%= p.label :client, "Client name: " %><br>
<%= collection_select(:client_id, :name, current_user.clients, :id, :name) %></li>
<li><%= p.submit "Create project", class: "form-button" %>, or <%= link_to "Cancel",
root_path %></li>
</ul>
</div>
<% end %>
</div>
項目模型
class Project < ActiveRecord::Base
belongs_to :client
end
您必須在表單構建器上調用collection_select
:
# change this
<%= collection_select(:client_id, :name, current_user.clients, :id, :name) %>
# to this
<%= p.collection_select(:client_id, current_user.clients, :id, :name) %>
通過使用FormBuilder p
您可以告訴collection_select
您正在編輯Project對象(請參閱p.object
以返回表單構建器的對象)。
如果您查看collection_select
文檔( http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select ):
collection_select(對象,方法,集合,value_method,text_method,options = {},html_options = {})
如果您單獨調用collection_select
(不是從form_for
方法提供的表單生成器中調用),則必須將對象的名稱作為第一個參數。 在您的情況下,可能是collection_select(:project, :client_id, #etc.)
來生成params[:project][:client_id]
類的params[:project][:client_id]
。
要收費,您需要在project_params
修復您的錯字
對於client_id,請嘗試以下操作:
內部視圖/項目/新
<%= collection_select(:project, :client_id, current_user.clients, :id, :name) %>
要么
<%= p.collection_select(:client_id, current_user.clients, :id, :name) %>
當您使用collection_select
,前兩個參數是集合描述的對象和屬性(在本例中為您的project
對象和client_id
屬性),因此當您編寫collection_select(:client_id, :name, current_user.clients, :id, :name)
Rails實際上收到了一個看起來像{ client_id: {name: 'Something'} }
的對象,而您完全忽略了它,而我的代碼將:client_id添加到項目對象中,這正是您的代碼所期望的。
使用表單構建器(在本例中為p
對象)可以省略“對象”參數,因為表單構建器已經知道要為其構建表單的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.