【问题标题】:how to associate two models using has_many and belongs_to ruby on rails如何在rails上使用has_many和belongs_to ruby​​关联两个模型
【发布时间】:2015-12-11 11:09:36
【问题描述】:

我在我的应用程序中生成了两个模型 tour 和 tourcategories。现在我想使用has_manybelongs_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 &lt; 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


    【解决方案1】:

    你定义了,
    Tourcategory 有多个游览。 has_many :tours
    Tour 属于一个 Tourcategory。 belongs_to :tourcategory

    因此,您不能从@tour 调用tourcategories。你可以从@tour拨打tourcategory

    另外,
    @tour.build_tour build_* 方法来处理belongs_to 关系。
    我觉得你应该试试@tour.build_tourcategory

    阅读 Rails 指南中的“动作记录关联”部分:http://guides.rubyonrails.org/association_basics.html

    【讨论】:

      【解决方案2】:

      您不能调用@tour.tourcategories,因为Tour 属于单个Tourcategory,因此Rails 不会生成该方法。您可以致电@tour.tourcategory@tourcategory.tours

      你为什么还要将第四个参数传递给options_for_collection_from_selectmap 方法将返回一个集合,但您需要一个元素。尝试省略它,看看它是否有效。

      您的代码还有几个问题:

      @tour.build_tour 将不起作用,除非您明确定义了该方法(如果您有,最好将其命名为其他名称)。所有build_something 方法都是为has_one 关系生成的。也许你正在寻找@tourcategory.tours.build

      您不应从视图中调用Tourcategory.all,而应使用您在控制器中定义的@tourcategories 变量。视图不应该直接调用模型。

      如果您使用的是 Rails 4,则不应使用 attr_accessible,而应在控制器中定义强参数。

      希望对您有所帮助。

      【讨论】:

        【解决方案3】:

        您实际上需要使用 HABTM(Has And Belongs To Many) - 请查看Rails documentation 了解更多详情

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-21
          • 2015-09-11
          • 1970-01-01
          • 2017-09-25
          • 1970-01-01
          相关资源
          最近更新 更多