簡體   English   中英

Rails:通過未填充的表單進行的belongs_to關聯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM