繁体   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