2016-12-30 100 views
0

我的項目中有幾個模型: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列總是空的,它不保存類名。可能是什麼問題?有任何想法嗎?

+1

你能提供你正在使用的代碼在'works'表中創建一行嗎?例如'Work.create'或'Employee.new(...).save'? – coreyward

+0

在'has_many:requests'你爲什麼要加'as:performer'? 「通過」應該足夠了。 – Deep

回答

2

它是空的,因爲你我以前不通過它,你應該添加一個隱藏字段,用於形成:你必須通過performer_id:

<%= 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 %> 
+0

我總是通過多態關聯類型來爲你計算rails的東西 – Marat

0

除了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 

這是一個很好的例子(爲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?