Lynda Rails 3教程中的NoMethodError

时间:2013-05-06 14:46:09

标签: ruby-on-rails

有什么问题,我该如何解决?

运行me = AdminUser.find(1)然后运行me.section.edits

时出现以下错误
NoMethodError: undefined method `section' for #<AdminUser:0x007fa539ee0558>
   from ...gems/activemodel-3.2.13/lib/active_model/attribute_methods.rb:407:in `method_missing'
   from ...gems/activerecord-3.2.13/lib/active_record/attribute_methods.rb:149:in `method_missing'

我的代码

create_section_edits.rb

class SectionEdit < ActiveRecord::Base
  attr_accessible :title, :body, :name, :position
  belongs_to :editor, :class_name => "AdminUser", :foreign_key => 'admin_user_id'
  belongs_to :section
end

admin_user.rb

class AdminUser < ActiveRecord::Base
  attr_accessible :title, :body, :username, :first_name, :last_name
  has_and_belongs_to_many :pages
  has_many :section_edits
  scope :named, lambda {|first,last| where(:first_name => first, :last_name => last)}
end

section.rb

class Section < ActiveRecord::Base
  attr_accessible :title, :body, :name, :position
  belongs_to :page
  has_many :section_edits
end

section_edit.rb

class SectionEdit < ActiveRecord::Base
  attr_accessible :title, :body, :name, :position
  belongs_to :editor, :class_name => "AdminUser", :foreign_key => 'admin_user_id'
  belongs_to :section
end

2 个答案:

答案 0 :(得分:1)

AdminUser与sections没有任何关系,但只与section_edits有关。

所以,而不是

me.section.edits

您需要使用

me.section_edits

答案 1 :(得分:0)

我认为您缺少的是管理员可以通过section_edits拥有多个部分。

您的关联需要看起来像这样

class AdminUser < ActiveRecord::Base
  attr_accessible :title, :body, :username, :first_name, :last_name
  has_and_belongs_to_many :pages
  has_many :section_edits
  has_many :sections, through: :section_edits
  scope :named, lambda {|first,last| where(:first_name => first, :last_name => last)}
end

注意has_many通过允许您拨打me.sections