Search code examples
ruby-on-railspolymorphic-associations

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.

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?


Solution

  • 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 %>