Ruby on rails 表单中的类别id-模型关联
我有两个模型:一个产品模型和一个类别模型,具有以下关联:Ruby on rails 表单中的类别id-模型关联,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有两个模型:一个产品模型和一个类别模型,具有以下关联: class Product < ActiveRecord::Base belongs_to :category validates :title, presence: true end class Category < ActiveRecord::Base attr_accessible :name has_many :products end 类产品
class Product < ActiveRecord::Base
belongs_to :category
validates :title, presence: true
end
class Category < ActiveRecord::Base
attr_accessible :name
has_many :products
end
类产品
当我尝试使用simple_form创建新产品时,在category_id字段中,我希望获得类别的名称,而不是类别的id
<%= simple_form_for @product do |f| %>
<%= f.input :title %>
<%= f.input :description %>
<%= f.input :price %>
<%= f.input :category_id %>
<%= f.button :submit %>
<% end %>
我该怎么做呢?我相信你会有这样的想法:
<%= simple_form_for @product do |f| %>
<%= f.input :title %>
<%= f.input :description %>
<%= f.input :price %>
<%= f.association :category, collection:
Category.all, prompt: "Choose a category"%>
<%= f.button :submit %>
<% end %>
我确实可以工作,但是拥有类别好吗?所有的都在视图中吗?@DaveTheGray我想你可以侥幸逃脱,只要你的视图不是这样的-这是一个非常受欢迎的博客。从第一个例子来看,视图中有很多逻辑。但是很多人会说,把你的逻辑控制在最低限度。谢谢,只是你回答的类别中的一个小错误。所有的谢谢,我已经改变了这一点。