has_many:通过关系解释

时间:2012-12-14 23:40:04

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

我是Rails的新手,对我需要使用的那种关系有一些疑问。情况就是这样。

我有两个型号Offer和User,一个用户可以属于很多优惠和优惠可以有很多用户。用户也会创建优惠。

我想我必须使用has_many:通过关系。例如,我创建了另一个模型“申请人”。申请人are_to用户和belongs_to offer。但是从用户和提供模型的关系如何?例如:

用户模型

 has_many :offer, :through => :applicant

提供型号

 has_many :user, :through => :applicant

我怀疑是因为我已经有了这两种关系

用户模型

has_many :offers, :dependent => :destroy

提供型号

belongs_to :user

解决这个问题之后,我请客人从applicanst_controller中保存申请人模型中的记录,对吗?

提前致谢

1 个答案:

答案 0 :(得分:3)

您所描述的是使用连接表的many-to-many关系。您实际上非常接近,但您只需要从您的用户模型和商品模型中的has_many :offers, :dependent => :destroy中移除blongs_to :user即可。看起来应该是这样的:

class User < ActiveRecord::Base
  has_many :offers, :through => :applicants
end

class Applicant < ActiveRecord::Base
  belongs_to :users
  belongs_to :offers
end


class Offer < ActiveRecord::Base
  has_many :users, :through => :applicants
end

您不必担心依赖性破坏部分,因为在删除相应对象时会自动删除关联。通过多对多关联,如何建立关系并不重要。以下任何一种都可以使用:

@user.offers << @offer

@offers.users << @user

如果您不需要存储特定于申请人加入表的任何信息(例如,时间戳,描述),您可能希望查看has_and_belongs_to_many关系。查看choosing between has_many_through and has_and_belongs_to_many以供参考。

修改

以下是HABTM关系的代码:

class User < ActiveRecord::Base
  has_and_belongs_to_many :offers
end


class Offer < ActiveRecord::Base
  has_and_belongs_to_many :users
end
相关问题