[英]Rails polymorphic association won't save _type
I have a few models in my project : Request, Work, Car and Employee. 我的项目中有几个模型:请求,工作,汽车和员工。 Work is an intermediate model between Request and Car/Employee.
工作是Request和Car / Employee之间的中间模型。
Here are the associations: 以下是关联:
Request 请求
has_many :works, dependent: :destroy
def performers
works.map {|x| x.performer}
end
Work 工作
belongs_to :request
belongs_to :performer, polymorphic: true
Car 汽车
has_many :works, as: :performer
has_many :requests, through: :works, as: :performer
Employee 雇员
has_many :works, as: :performer
has_many :requests, through: :works, as: :performer
View used to create works: 用于创建作品的视图 :
<%= form_for([@request, @work]) do |f| %>
<%= (f.collection_select :performer_id, Employee.all, :id, :name) if @request.type == "StaffRequest" %>
<%= (f.collection_select :performer_id, Car.all, :id, :select_info) if @request.type == "CarRequest" %>
<%= f.submit 'OK' %>
<% end %>
Work controller 工作控制器
def new
@work = @request.works.new
end
def create
@work = @request.works.new(work_params)
end
def work_params
params.require(:work).permit(:performer_id, :request_id)
end
The problem is that my performer_type column is always empty, it does not save the class name. 问题是我的performer_type列始终为空,它不保存类名。 What can be the problem?
可能是什么问题? Any ideas?
有任何想法吗?
It's empty because you did't pass it, you should add a hidden field for you form: 它是空的,因为您没有通过它,您应该为表单添加一个隐藏字段:
<%= form_for([@request, @work]) do |f| %>
<% if @request.type == "StaffRequest" %>
<%= (f.hidden_field :performer_type, value: "Employee") %>
<%= (f.collection_select :performer_id, Employee.all, :id, :name) %>
<% elsif @request.type == "CarRequest" %>
<%= (f.hidden_field :performer_type, value: "Car") %>
<%= (f.collection_select :performer_id, Car.all, :id, :select_info) %>
<% end %>
<%= f.submit 'OK' %>
<% end %>
Beside :performer_id, you have to pass the :performer_type also, one way to do this is via the form select_tag : 除了:performer_id之外,您还必须传递:performer_type,一种方法是通过select_tag形式:
def create
@work = @request.works.new(work_params)
end
def work_params
# use :performer if you use :performer as in the select form field
params.require(:work).permit(:performer, :request_id)
# OR
# use :performer_id & :performer_type if you also use the hidden field
params.require(:work).permit(:performer_id, :performer_type, :request_id)
end
There is a good example (for Rails 4.2) of using a single select form field for polymorphic so you can write like: 有一个很好的示例(对于Rails 4.2),将单个选择表单字段用于多态,因此您可以这样编写:
<%= f.grouped_collection_select :global_performer, [ Car, Employee ], :all, :model_name, :to_global_id, :name %>
How to create grouped select box in Rails for polymorphic association using Global ID? 如何使用全局ID在Rails中为多态关联创建分组选择框?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.