如何在rails上使用has_many和belongs_to ruby关联两个模型

贾斯普雷特·考尔(Jaspreet Kaur)

我在我的应用程序中生成了两个模型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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Rails Has_many和Belongs_to中的模型关联

如何使用has_many / belongs_to使Rails 4关联自动保存到两个表中?

Ruby on rails-使用JUST'belongs_to'与使用BOTH'has_many'和'belongs_to'之间的区别?

在Rails中命名两个关联has_many / belongs_to失败

如何在我的模型“ has_many”或“ belongs_to”关系属性中使用gem模型?

Rails:Rails Engine中的Belongs_to和Has_many关联

两个belongs_to关联迁移的相同模型

与Geocoder has_many和belongs_to关联的结果很奇怪

NoMethodError,has_many和belongs_to关联

ActiveRecord has_many和belongs_to在同一模型上

连接两个模型belongs_to / has_many并通过下拉菜单进行选择

Rails 4-两个模型之间的关联

两个模型之间有不同的关联Rails

如何同时保存两个彼此关联的模型?

使用has_many和belongs_to关联创建factory_girl对象时发生验证错误

我在作者(has_many)和书(belongs_to)上的 rails 中创建了一个关联,现在删除作者(依赖::destroy)后,我得到了异常

RoR和Postgresql DB:belongs_to关联有效,但has_many无效

ActiveRecord has_one 其中关联模型有两个所属关联

关联的has_many的belongs_to通过未被识别

两个红宝石模型。has_one,和belongs_to。为什么要有两个模型?

Rails:如何在两个模型之间建立多重关联

将 Rails 活动模型与两个不同的模型相关联

FactoryGirl 与belongs_to / has_many 关联,至少有 1 个关联

Rails-has_one与两个可能模型之一的关联

使用“where”关联has_one和belongs_to模型

我如何在两个模型之间具有多个has_many到has_many关系?

使用嵌套表单通过一个提交按钮更新两个非关联模型

Rails 5,如何用关联表命名两个模型?

Rails 5.2 - 如何将报告模型与两个用户相关联