Rails 4.2.0 HABTM NoMethodError

时间:2015-07-15 22:51:10

标签: ruby-on-rails ruby postgresql

我的模特遇到has_and_belongs_to_many问题。

以下是设置:

  • Ruby - 2.2.0
  • Rails - 4.2.0
  • PostgreSQL - 9.4.4

我有以下型号:

class Series < ActiveRecord::Base
   # has_many :series_labels
   # has_many :labels, through: :series_labels
   has_and_belongs_to_many :labels
   has_many :videos
end

class Label < ActiveRecord::Base
  # has_many :series_labels
  # has_many :series, through: :series_labels
  has_and_belongs_to_many :series
end

class LabelSeries < ActiveRecord::Base
  belongs_to :series
  belongs_to :label
end

我有以下迁移:

class CreateSeries < ActiveRecord::Migration
  def change
    create_table :series do |t|

      t.timestamps null: false
    end
  end
end

class AddColumnsToSeries < ActiveRecord::Migration
  def change
    add_column :series, :asset_type, :string
    add_column :series, :duration, :integer
    add_column :series, :external_id, :string
    add_column :series, :asset_created_at, :datetime
    add_column :series, :asset_updated_at, :datetime
    add_column :series, :asset_status, :string
    add_column :series, :asset_hosted_at, :string
    add_column :series, :original_file_name, :string
  end
end

class CreateLabels < ActiveRecord::Migration
  def change
    create_table :labels do |t|
      t.string :value

      t.timestamps null: false
    end
  end
end

class CreateLabelsSeries < ActiveRecord::Migration
  def change
    create_join_table :labels, :series do |t|
      t.index :label_id
      t.index :series_id
    end
  end
end

当我运行rails c并提供以下内容时:

s = Series.where(displayName: 'Some Series Name')
s.labels

我收到以下错误:

  

NoMethodError:

的未定义方法`标签'      来自/Users/johnhenderson/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.0/lib/active_record/relation/delegation.rb:136:in      

method_missing' from /Users/johnhenderson/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.0/lib/active_record/relation/delegation.rb:99:in method_missing'来自(irb):2来自   /Users/johnhenderson/.rvm/gems/ruby-2.2.0/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in   start' from /Users/johnhenderson/.rvm/gems/ruby-2.2.0/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in 从'开始'   /Users/johnhenderson/.rvm/gems/ruby-2.2.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in   console' from /Users/johnhenderson/.rvm/gems/ruby-2.2.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in run_command!”从   /Users/johnhenderson/.rvm/gems/ruby-2.2.0/gems/railties-4.2.0/lib/rails/commands.rb:17:in   <top (required)>' from bin/rails:4:in需要'来自bin / rails:4:in   `'

最好我可以告诉所有设置都正确,并且数据库中的所有表都有值。

感谢您的帮助, 约翰

1 个答案:

答案 0 :(得分:1)

这里的问题是Series.where(displayName: 'Some Series Name')返回Series个对象的集合。如果您只想要一个系列记录,请使用:

s = Series.where(displayName: 'Some Series Name').first

s = Series.find_by(displayName: 'Some Series Name')