Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 表单中的类别id-模型关联_Ruby On Rails_Ruby - Fatal编程技术网

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我想你可以侥幸逃脱,只要你的视图不是这样的-这是一个非常受欢迎的博客。从第一个例子来看,视图中有很多逻辑。但是很多人会说,把你的逻辑控制在最低限度。谢谢,只是你回答的
类别中的一个小错误。所有的
谢谢,我已经改变了这一点。