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

发布于 2024-12-17 10:10:41 字数 1221 浏览 6 评论 0原文

大家好,我有一个 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

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

当我保存膳食类型时,它不会出现在客户端上index.html.erb(空白)。 问题是什么? 我如何通过使用以下控制器为客户提供膳食类型(例如“午餐”)来创建客户:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖 2024-12-24 10:10:41

问题是我只需在 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

所以现在我可以在创建客户端时选择膳食类型。
感谢 Anan解决方案来自他。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文