我有一个User
模型,如下所示
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable
has_many :company_users
accepts_nested_attributes_for :company_users, :allow_destroy => true
has_many :companies, :through => :company_users
has_many :roles, :through => :company_users
end
及其相关模型CompanyUser
如下,
class CompanyUser < ActiveRecord::Base
belongs_to :user
belongs_to :company
belongs_to :role
end
我正在尝试构建如下的关联,但似乎无法正常工作
# GET /users/new
def new
@user = User.new
@user.company_users.build
end
查看文件如下,
<%= form_for(@user) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br>
<%= f.text_field :email %>
</div>
<h3>Companies and Roles</h3>
<div class="field">
<% f.fields_for :company_users do |cu| %>
<p>
<%= cu.label :company_id %>
<%= cu.text_field :company_id%>
<%= cu.label :role_id %>
<%= cu.text_field :role_id %>
<%= cu.check_box :_destroy %>
<%= cu.label :_destroy, 'delete' %>
</p>
<% end %>
<p>
<%= f.submit 'Add to user', :name => "add_company_user" %>
<%= f.submit 'Delete from user', :name => "remove_company_user" %>
</p>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我想弄清楚它出了什么问题。
答案 0 :(得分:4)
您错过了=
,因此fields_for
块未呈现给该页面。改变这一行
<% f.fields_for :company_users do |cu| %>
到
<%= f.fields_for :company_users do |cu| %>