【问题标题】:Ruby on Rails 3.1: Am I setting this relationship up correctly?Ruby on Rails 3.1:我是否正确设置了这种关系?
【发布时间】:2011-12-15 00:28:08
【问题描述】:

我正在 Ruby on Rails 3.1 中制作我的第一个应用程序......我是否正确设置了这些关系?本质上,学生/客户将能够登录并评价老师。一个客户可以有很多老师,一个老师可以有很多客户。每个客户都可以为特定教师创建评分(教师不能对客户进行评分)。评级是可选的。

我打算能够显示来自不同客户的教师评分,并允许客户登录并对他们拥有的所有教师进行评分。

class Client < ActiveRecord::Base
  has_many :ratings
  has_and_belongs_to_many :teachers
end

class Teacher < ActiveRecord::Base
  has_many :ratings
  has_and_belongs_to_many :clients
end

class Rating < ActiveRecord::Base
  belongs_to :teacher
  belongs_to :client
end

【问题讨论】:

    标签: ruby-on-rails ruby relationships


    【解决方案1】:

    我想说has_and_belongs_to_many 的用法应该在您只有一个数据库表而不是Rails 模型来连接模型时使用。就您而言,既然您确实有一个名为 Rating 的模型,那么我会说最好使用 has_many, :through

    为此,请将您的教师和客户模型更改为如下所示:

    class Client < ActiveRecord::Base
      has_many :ratings
      has_many :teachers, :through => :ratings
    end
    
    class Teacher < ActiveRecord::Base
      has_many :ratings
      has_many :clients, :through => :ratings
    end
    

    Rating 模型不需要任何更改。

    【讨论】:

    • 谢谢,我认为我遇到了麻烦,因为我认为您不能使用 has_many :through 因为客户可能无法评价老师,但我看到了我的想法中的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多