在我的应用程序中,我已经生成了两个模型旅游和旅游类别。现在,我想使用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这是旅游迁移文件的定义:类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发布于 2015-12-11 11:15:47
您实际上需要使用HABTM (拥有和属于许多)-请查看Rails文档以获得更多详细信息
发布于 2015-12-12 08:49:57
你定义了,
旅游类别有多个旅行团。has_many :tours
旅游属于一个旅游范畴。belongs_to :tourcategory
因此,您不能从tourcategories调用@tour。您可以从tourcategory从@tour调用
另外,
@tour.build_tour <-可能会出错。您可以对build_*关系使用belongs_to方法。
我觉得你应该试试@tour.build_tourcategory
阅读Rails指南中的“操作记录协会”一节:basics.html
发布于 2015-12-12 09:19:51
您不能调用@tour.tourcategories,因为Tour属于单个Tourcategory,因此Rails不会生成该方法。你可以打电话给@tour.tourcategory或@tourcategory.tours。
您为什么要将第四个参数传递给options_for_collection_from_select?该map方法将返回一个集合,但您需要一个元素。试着省略它,看看它是否有效。
您的代码还有几个问题:
除非您已经显式地定义了该方法,否则@tour.build_tour将无法工作(如果您已经定义了该方法,那么最好将它命名为其他方法)。所有build_something方法都是为has_one关系生成的。也许你在找@tourcategory.tours.build。
您不应该从视图中调用Tourcategory.all,而是使用您在控制器中定义的@tourcategories变量。视图不应该直接调用模型。
如果使用Rails 4,则不应该使用attr_accessible,而应该在控制器中定义强参数。
希望这能有所帮助。
https://stackoverflow.com/questions/34222139
复制相似问题