我有一个模型,我有用户,课程,我通过角色模型连接两个。一切似乎运作良好,我可以分配和检索学生,我可以检索一个老师,当我指定一个老师的课程。我收到错误
Course.last.teacher
# => <# User username: 'schneems' ...>
course = Course.new
course.students = User.last(3)
# => [<# User ... >, <# User ... >, <# User ... >]
course.teacher = User.first
# => NoMethodError: undefined method 'update_attributes' for #<Class:0x007f86b29ee838>
以下是我的基本模型
class User < ActiveRecord::Base
has_many :roles
has_many :courses, :through => :roles
end
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :course
end
class Course < ActiveRecord::Base
has_many :roles
has_one :teacher, :through => :roles, :source => :user, :conditions => ['roles.name = ?', 'teacher']
has_many :students, :through => :roles, :source => :user, :conditions => ['roles.name = ?', 'student']
end
完整堆栈跟踪如下所示:
NoMethodError: undefined method `update_attributes' for #<Class:0x007f86b29ee838>
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/base.rb:1014:in `method_missing'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/associations/association_collection.rb:444:in `block in method_missing'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/base.rb:1127:in `with_scope'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/associations/association_proxy.rb:207:in `with_scope'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/associations/association_collection.rb:440:in `method_missing'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/associations/has_one_through_association.rb:22:in `create_through_record'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/associations/has_one_through_association.rb:10:in `replace'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/activerecord-3.0.9/lib/active_record/associations.rb:1465:in `block in association_accessor_methods'
from (irb):43
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
from /Users/schneems/.rvm/gems/ruby-1.9.2-p290@hourschool/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
有谁知道如何让这个协会工作,我可以检索和设置课程的教师属性按预期?使用Rails 3.0.9
答案 0 :(得分:2)
如果您在Rails 3.1上运行此确切代码,您将收到以下错误消息:
ActiveRecord :: HasOneThroughCantAssociateThroughCollection:不能拥有 a has_one:通过关联'Course#teacher'所在的地方:通过 协会'课程#角色'是一个集合。指定has_one或 相反,在:through选项中的belongs_to关联。
此处使用的正确关联是belongs_to
,但在这种情况下,您无法将其放入角色表中。
问候丹尼尔
答案 1 :(得分:0)
尝试将:class_name => "User"
添加到Course
上的:教师协会。