我想在我的应用程序中实现MTI。我有一个Person Model和2个继承自它的模型:Client和TeamMember。在创建团队成员时,我想保存到人员(名字和姓氏,电子邮件等)和团队成员(经验等级,团队类型,如果是否带领)的数据库故障。我正在使用嵌套属性表单,因此在我的团队成员表单中,我正在嵌套人员字段。不幸的是,我在尝试保存时遇到“无法大量分配受保护的属性:人”错误。谁能告诉我这是如何解决的?谢谢! 机型:
UPDATED TeamMember类,但仍然是同样的错误 还尝试过people_attributes和persons_attributes,但这些都没有效果
class TeamMember < ActiveRecord::Base
has_many :project_team_members
has_many :projects, through: :project_team_members
has_one :person, as: :profile, dependent: :destroy
accepts_nested_attributes_for :person
attr_accessible :person_attributes, :experience_level, :lead, :qualification, :team
end
class Person < ActiveRecord::Base
belongs_to :company
belongs_to :profile, polymorphic: true
attr_accessible :email, :first_name, :last_name, :phone_number, :profile_id, :profile_type
end
控制器如下:
class TeamMembersController < ApplicationController
def create
person = Person.create! { |p| p.profile = TeamMember.create!(params[:team_member]) }
redirect_to root_url
end
和视图:
<%= form_for(@team_member) do |f| %>
<%= f.fields_for :person do |ff| %>
<div>
<%= ff.label :first_name %>
<%= ff.text_field :first_name %>
</div>
<div>
<%= ff.label :last_name %>
<%= ff.text_field :last_name %>
</div>
<div>
<%= ff.label :phone_number %>
<%= ff.text_field :phone_number %>
</div>
<div>
<%= ff.label :email %>
<%= ff.text_field :email %>
</div>
<div>
<%= ff.label :company_id %>
<%= ff.text_field :company_id %>
</div>
<% end %>
<div class="field">
<%= f.label :team %><br />
<%= f.text_field :team %>
</div>
<div class="field">
<%= f.label :experience_level %><br />
<%= f.text_field :experience_level %>
</div>
<div class="field">
<%= f.label :qualification %><br />
<%= f.text_field :qualification %>
</div>
<div class="field">
<%= f.label :lead %><br />
<%= f.check_box :lead %>
</div>
<div class="actions">
<%= f.submit %>
</div>
UPDATED TeamMembersController(感谢Tiago提供的解决方案)
def new
@team_member = TeamMember.new
@team_member.build_person
respond_to do |format|
format.html # new.html.erb
format.json { render json: @team_member }
end
end
def create
@team_member = TeamMember.create!(params[:team_member])
redirect_to root_url
end
答案 0 :(得分:1)
要以嵌套形式批量指定属性,您需要指定:
class TeamMember < ActiveRecord::Base
has_many :project_team_members
has_many :projects, through: :project_team_members
has_one :person, as: :profile, dependent: :destroy
:experience_level, :lead, :qualification, :team #what is this line doing??
accepts_nested_attributes_for :person
attr_accessible :person_attributes
end
编辑:
在表单之前调用的操作中,您需要构建人员。像:
@team_member = TeamMember.new
@team_member.build_person
然后您将有一个人(非持久性)与@team_member相关联。