使用下拉菜单将值从一个模型传递到另一个模型

时间:2013-07-25 07:32:45

标签: ruby-on-rails-3

型号:

product.rb:

class Product < ActiveRecord::Base
  attr_accessible :cat_id, :id, :name
  belongs_to :category
end

category.rb:

class Category < ActiveRecord::Base
  attr_accessible :id, :name
  has_many :products
end

路线:

的routes.rb

resources :categories do
  resources :products
end

我想将产品添加到类别中。在控制器和产品视图中写什么请帮忙! 请!!我是铁轨的初学者!

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作,

如果您的路径(网址)应该与http://loaclhost:3000/category/1/produts类似,请使用您网址中的id params

将cateogry id传递给产品视图 form.erb

<%= f.hidden_field :cat_id , :value => <pass catogory id from routes url> %>

然后按照常用的创建方法(请检查对象是否创建了cat_id)

现在,您可以从产品的cat_id访问类别值。

希望它会有用。

答案 1 :(得分:0)

如果你想要一个下拉菜单:

_file.html.haml

  = label_tag :Category
   = select_tag "product[category_id]", options_from_collection_for_select(@categories, :id,:name,@selected = @product[:category_id] :include_blank => true

products_controller.rb:

before_filter :get_categories, :only => [:new,:edit]


def get_categories
   @categories = Category.all
end
相关问题