在创建视图和控制器上访问STI类型

时间:2011-11-21 18:13:14

标签: ruby-on-rails types view sti

大家好,我有2个模特客户和餐。

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

视图/客户端/ _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 %>

当我保存膳食类型时,它不会出现在客户端'index.html.erb上(它是空白的)。 问题是什么? 如何通过以下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

1 个答案:

答案 0 :(得分:0)

重要的是我只需在 meal.rb 中设置列继承,如下所示:

class Meal < ActiveRecord::Base

    set_inheritance_column do
        "type" + "_id"
    end 

belongs_to :client
end

class Lunch < Meal
end

class Dessert < Meal
end

所以现在我可以在创建客户端时选择用餐类型。 感谢Anansolution来自他。