Search code examples
ruby-on-railstypesviewsti

Acces STI type on create view and controller


Hello guys I've a a 2 model client and meal.

client.rb

class Client < ActiveRecord::Base

has_many :meals
accepts_nested_attributes_for :meals

end

meal.rb

class Meal < ActiveRecord::Base
belongs_to :client
end

class Lunch < Meal
end

class Dessert < Meal
end

views/clients/_form.html.erb

    <%= simple_form_for @client do |f| %>

    <%=f.input :name %>
    <%=f.input :adress %>
    <%=f.input :telephone %>

   <%= f.simple_fields_for :meal do |m| %>
    <%=m.input :type %>
    <%end%>
  <% end %>

When I save the meal type it doesn't appear on client' index.html.erb(it's blank). What the problem is? How can I create a client by giving him a meal type(eg."Lunch") with the following cotroller:

def create
  @client = Client.new(params[:client])

  respond_to do |format|
  if @client.save
    format.html { redirect_to @client, notice: 'Operation was successfully created.' }
    format.json { render json: @client, status: :created, location: @client }
  else
    format.html { render action: "new" }
    format.json { render json: @client.errors, status: :unprocessable_entity }
  end
  end
end

Solution

  • Matter i simply have to set the column inheritance in meal.rb like this:

    class Meal < ActiveRecord::Base
    
        set_inheritance_column do
            "type" + "_id"
        end 
    
    belongs_to :client
    end
    
    class Lunch < Meal
    end
    
    class Dessert < Meal
    end
    

    So now I can select the type of meal when I create a client. Thanks to Anan, the solution comes from him.