Rails:从其他模型添加表单

时间:2018-07-20 09:20:12

标签: ruby-on-rails ruby forms associations partial

在我的Rails应用程序中,我有一个项目模型,其中可以包含许多项目消息。

project has_many project_messages

projects/show.html.erb中,我想显示该项目的所有项目消息,但还要从该视图创建新的项目消息。 目前,我无法从该视图创建新的项目消息。

我查看了许多链接,但对我没有用 Adding Form For Different Model In Same ViewRails: Show form from different model in a view

我的projects/show.html.erb文件引用如下:

<div>
 <% render partial: 'project_messages/form', :object => @project_message %>
</div>

projects_controller.rb文件中,我包括以下内容:

  def show
    @project_message = ProjectMessage.new
  end

def project_params
  params.require(:project).permit(:title, :description, :phase_id, :RAGStatus, :currentpphase_id,  :project_messages_attributes => [:pMessage, :user_id, :project_id])
end

project.rb文件中,我还具有以下代码:

accepts_nested_attributes_for :project_messages

project_messages / _form.html.erb

<%= form_with(model: project_message, local: true) do |form| %>
  <% if project_message.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(project_message.errors.count, "error") %> prohibited this project_message from being saved:</h2>

      <ul>
      <% project_message.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%= form.label :pMessage %>
<%= form.text_field :pMessage, id: :project_message_pMessage, :class => 'au-input au-input--full au-input--h65', placeholder: 'Type a message' %>
  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

project_messages表单的局部部分无法呈现,因此我无法从该视图添加新消息。

错误:

undefined local variable or method `project_message' for #<#<Class:0x007f5455ced910>:0x007f5459ef8a30>
Did you mean?  @project_message

当我将@project_message添加到局部时,它不会呈现。

2 个答案:

答案 0 :(得分:0)

project_messages/_form.html.erb中,此行:

<%= form_with(model: project_message, local: true) do |form| %>

应更改为此:

<%= form_with(model: object, local: true) do |form| %>

您已将局部变量object分配给了局部变量,因此应使用它。

此外,也可以这样称呼偏体:

<% render partial: 'form', object: @project_message %>

答案 1 :(得分:0)

通常,在渲染局部像时:

<% render partial: 'form', object: @project_message %>

由于您将@project_message作为特殊命名的object参数进行传递,因此这会创建一个特殊的变量,其部分名称为form

因此,在部分变量中,您可以引用此变量:

<%= form_with(model: form, local: true) do |form| %>

...但是,在这种情况下,调用局部变量form真的没有意义!因此,我倾向于使用您要传入的任何名称,例如,您可以这样做:

<% render partial: 'form', project_message: @project_message %>

然后在部分中:

<%= form_with(model: project_message, local: true) do |form| %>

有关更多信息,请参见:http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables