我正在一个有会员的网站上工作。每个成员都有订阅。对于订阅,会员需要选择有3个的计划。
这是进行关联的正确方法吗
class Member < ActiveRecord::Base
has_one :plan, :through => :subscription
end
class Subscription < ActiveRecord::Base
belongs_to :member
has_many :plans
end
class Plan < ActiveRecord::Base
belongs_to :subscription
end
然后可能是这样的
member.plan
将是会员订阅的计划。
答案 0 :(得分:0)
如果某个成员一次可以属于一个计划,您可以按如下方式重做模型:
class Member < ActiveRecord::Base
has_one :subscription
has_one :plan, :through => :subscription
end
class Subscription < ActiveRecord::Base
belongs_to :member
belongs_to :plan
end
class Plan < ActiveRecord::Base
belongs_to :subscription
has_many :members
end
其他解决方案是通过向Subscription
表添加plan_id
列来完全避免members
模型。
# has a column called plan_id
class Member < ActiveRecord::Base
has_one :plan
end
class Plan < ActiveRecord::Base
has_many :members
end