【发布时间】:2015-12-11 11:09:36
【问题描述】:
我在我的应用程序中生成了两个模型 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
这是旅游类别模型的定义:
class Tourcategory < ActiveRecord::Base
has_many :tours
attr_accessible :title
end
这是 tours 迁移文件的定义:
班级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
【问题讨论】:
标签: ruby-on-rails ruby has-many model-associations belongs-to