2013-03-18 77 views
13

我有兩個模型,投訴和公司。投訴belongs_toaccepts_nested_attributes公司和公司has_many投訴。belongs_to關聯欄的嵌套屬性

# 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 %> 

表單提交,但只保存投訴。公司的用戶輸入被忽略。爲什麼這不會創建一個新的公司?

+0

喜@pjmil前f.,我面臨着同樣的problem.will請你告訴我的投訴控制器強參數? – 2016-03-30 20:50:17

+0

嗨,我面臨同樣的問題。你怎麼修好它的。 – aashish 2016-12-10 13:17:41

回答

17

我的錯誤是在形式。我錯過了fields_for :company

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