我的項目中有幾個模型:Request,Work,Car和Employee。工作是Request和Car/Employee之間的中間模型。Rails多態關聯不會保存_type
這裏有關聯:
請求
has_many :works, dependent: :destroy
def performers
works.map {|x| x.performer}
end
工作
belongs_to :request
belongs_to :performer, polymorphic: true
汽車
has_many :works, as: :performer
has_many :requests, through: :works, as: :performer
員工
has_many :works, as: :performer
has_many :requests, through: :works, as: :performer
查看用於創建工程:
<%= 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 %>
工作控制器
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
的PROBL em是我的performer_type列總是空的,它不保存類名。可能是什麼問題?有任何想法嗎?
你能提供你正在使用的代碼在'works'表中創建一行嗎?例如'Work.create'或'Employee.new(...).save'? – coreyward
在'has_many:requests'你爲什麼要加'as:performer'? 「通過」應該足夠了。 – Deep