如何从has_and_belongs_to_many获取记录

时间:2013-08-24 21:32:48

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 has-and-belongs-to-many

我有两个模型HotelTheme,我在其上应用了has_and_belongs_to_many关联。

我的迁移是

class CreateHotelsThemesTable < ActiveRecord::Migration
  def up
    create_table :hotels_themes, :id => false do |t|
        t.references :hotel
        t.references :theme
    end
    add_index :hotels_themes, [:hotel_id, :theme_id]
    add_index :hotels_themes, :hotel_id
  end

  def down
    drop_table :hotels_theme
  end
end

模特是:

class Theme < ActiveRecord::Base
  attr_accessible :theme_names
  has_and_belongs_to_many :hotels
end



class Hotel < ActiveRecord::Base
  attr_accessible :hotel_name, :stars, :location
  validates :hotel_name, :stars, :location, :presence => true
  has_and_belongs_to_many :thumes
end

有些记录是:

theme
=> #<Theme id: 5, theme_names: "Friends", created_at: "2013-08-24 20:13:00", updated_at: "2013-08-24 20:13:00">

    hotel
=> #<Hotel id: 2, hotel_name: "vijay shree1", stars: "2", location: "South Goa", created_at: "2013-08-24 15:59:53", updated_at: "2013-08-24 15:59:53">

当我跑步时

>> theme.hotels
=> [#<Hotel id: 2, hotel_name: "vijay shree1", stars: "2", location: "South Goa", created_at: "2013-08-24 15:59:53", updated_at: "2013-08-24 15:59:53">]

工作但我跑的时候

>> hotel.themes
!! #<NoMethodError: undefined method `themes' for #<Hotel:0x007f6cd007c080>>

我不知道为什么会发生这种情况我使用了has_and_belongs_to_many关联。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

似乎有一个拼写错误:has_and_belongs_to_many :thumes

我认为这是你问题的原因