我在我的应用程序中生成了两个模型tour和tourcategories。现在,我想使用has_many
和关联这两个模型belongs_to
。其中,游览可以与单个游览类别相关,但是游览类别可以具有多个游览。因此,该tour
模型的定义如下:
class Tour < ActiveRecord::Base
belongs_to :tourcategory
attr_accessible :content, :element_id, :job_id, :title, :priority, :tourcategory
end
这是tourcategory模型的定义:
class Tourcategory < ActiveRecord::Base
has_many :tours
attr_accessible :title
end
这是游览迁移文件的定义:class CreateTours < ActiveRecord::Migration
def change
create_table :tours do |t|
t.string :element_id
t.string :title
t.text :content
t.integer :job_id
t.integer :priority
t.belongs_to :tourcategory, index:true
t.timestamps
end
end
end
这是游览控制器的定义:
def new
@tourcategories = Tourcategory.all
@tour = Tour.new
@tour.build_tour
respond_to do |format|
format.html
format.json { render json: @tour }
end
end
现在我得到一个错误
undefined method `tourcategories'
当我访问_form.html.haml
视图进行编辑和添加新游览时。这是遇到错误的代码。
.field
= label_tag "tour Categories"
%br/
= select_tag "tourcategory", options_from_collection_for_select(Tourcategory.all, 'id', 'title', @tour.tourcategories.map{ |j| j.id })
= f.submit
您实际上需要使用HABTM(有很多)-请查看Rails文档以获取更多详细信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句