【问题标题】:Nested attributes for belongs_to association railsbelongs_to 关联导轨的嵌套属性
【发布时间】:2013-03-18 06:46:36
【问题描述】:

我有两个模型,投诉和公司。公司投诉belongs_toaccepts_nested_attributes,公司投诉has_many

# Models

class Complaint < ActiveRecord::Base
  attr_accessible :complaint, :date, :resolved

  belongs_to :user, :class_name => 'User', :foreign_key => 'id'
  belongs_to :company, :class_name => 'Company', :foreign_key => 'id'
  has_many :replies

  accepts_nested_attributes_for :company

end

class Company < ActiveRecord::Base
  attr_accessible :name

  has_many :complaints, :class_name => 'Complaint', :foreign_key => 'id'
  has_many :branches, :class_name => 'Branch', :foreign_key => 'id'
  belongs_to :industry

end

在投诉控制器中,我尝试使用新方法建立公司。

# Complaint Controller

class ComplaintsController < ApplicationController
...
def new
    @complaint = Complaint.new
    @complaint.build_company

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @complaint }
    end
  end
...
end

在表单中,我添加了一个字段,用于向公司添加名称属性。

# Complaint Form

<%= form_for(@complaint) do |f| %>
  <% if @complaint.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@complaint.errors.count, "error") %> prohibited this complaint from being saved:</h2>

      <ul>
      <% @complaint.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :complaint %><br />
    <%= f.text_area :complaint, :rows => 5 %>
  </div>
  <div class="field">
    <%= f.label :date %><br />
    <%= f.datetime_select :date %>
  </div>

  <% if current_user.try(:admin?) %>
    <div class="field">
      <%= f.label :resolved %><br />
      <%= f.check_box :resolved %>
    </div>
  <% end %>

  <%= fields_for :company do |company| %>
    <div class="field">
      <%= company.label :name, 'Company' %>
      <%= company.text_field :name %>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

表单提交但仅保存投诉。公司的用户输入被忽略。为什么这不会创建一个新公司?

【问题讨论】:

  • 嗨@pjmil,我也面临同样的问题。你能告诉我投诉控制器的强参数吗?
  • 嗨,我也面临同样的问题。你是怎么解决的。
  • @pjmil 非常感谢你的帖子。但是,您能否分享一下您的强大参数。另外,如果可能的话,您能否分享您在提交表单时获得的参数?谢谢

标签: forms ruby-on-rails-3.2 has-many belongs-to rails-models


【解决方案1】:

我的错误在于表格。我错过了fields_for :company之前的f.

<%= f.fields_for :company do |company| %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多