【发布时间】:2012-01-10 17:13:56
【问题描述】:
我有一个模型,其中有用户、课程,我通过角色模型将两者连接起来。一切似乎都运行良好,我可以分配和检索学生,当我为课程分配教师时,我可以检索教师。我收到一个错误
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
【问题讨论】:
-
我不知道是不是问题,但您只有
User <-> Role关联的一侧。你需要has_many :rolesinUser。 -
已更新,没有任何改变
标签: ruby-on-rails ruby activerecord