【问题标题】:Rails HABTM middle valuesRails HABTM 中间值
【发布时间】:2012-12-12 15:36:26
【问题描述】:

我必须遵循以下关系:

class Course < ActiveRecord::Base
  attr_accessible :name
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  attr_accessible :name
  has_and_belongs_to_many :courses
end

然后我有下表:

create_table :courses_users, :force => true, :id => false do |t|
  t.integer :user_id
  t.integer :course_id
  t.integer :middle_value
end

如何访问(编辑/更新)多对多记录中的中间值?

【问题讨论】:

    标签: ruby-on-rails ruby has-and-belongs-to-many


    【解决方案1】:

    HABTM 应该只用于存储关系。如果您有任何要存储在关系中的字段,您应该创建另一个模型,例如。 CourseSignup。然后,您将使用此模型创建 has_many :through =&gt; :course_signups 关系,因此您的模型将如下所示:

    class Course < ActiveRecord::Base
      has_many :course_signups
      has_many :users, :through => :course_signups
    end
    
    class CourseSingup < ActiveRecord::Base
      belongs_to :course
      belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_many :course_signups
      has_many :courses, :through => :course_signups
    end
    

    然后您可以在CourseSignup 模型中添加您的middle_value

    您可以在the guide to ActiveRecord associations找到更多详细信息。

    【讨论】:

      【解决方案2】:

      您想要的是 has_many :though,而不是 HABTM。

      HABTM 没有连接模型,但 has_many :through 有。比如:

      class Course < ActiveRecord::Base
        has_many :enrollments
        has_many :users, :through => :enrollments
      end
      
      class Enrollment < ActiveRecord::Base
        belongs_to :course
        belongs_to :user
      end
      
      class User < ActiveRecord::Base
        has_many :enrollments
        has_many :courses, :through => :enrollments
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多