1

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

当我运行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

部分.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
4

2 回答 2

1

AdminUser 与 没有关系sections,但section_edits仅与。

所以,而不是

me.section.edits

你需要使用

me.section_edits
于 2013-05-06T14:53:22.530 回答
0

I think what you are missing is the fact that Admins can have multiple sections through section_edits.

Your association needs to look like this

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

Note the has_many through allows you to call me.sections

于 2013-05-06T14:58:05.563 回答