Rails polymorphic association won't save _type

713 Views Asked by At

I have a few models in my project : Request, Work, Car and Employee. Work is an intermediate model between Request and 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. What can be the problem? Any ideas?

2

There are 2 best solutions below

1
On BEST ANSWER

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 %>
0
On

Beside :performer_id, you have to pass the :performer_type also, one way to do this is via the form 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:

<%= 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?