我是Rails的新手并且正在使用数据库,我想知道设置以下Active Record Association的最佳方式是什么。
我有以下表格:
我需要以下列方式将每个表与其他表相关联:
我最初认为我可以使用has_many:through association(在2.4:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association下看到),但是这种结构不允许在没有请求的情况下通过用户数据访问产品数据。
答案 0 :(得分:1)
class User < ActiveRecord::Base
has_many :requests
has_many :products
end
class Product < ActiveRecord::Base
has_many :requests
belongs_to :users
end
class Request < ActiveRecord::Base
belongs_to :requester, class_name: 'User'
belongs_to :requestee, class_name: 'User'
belongs_to :requester_product, class_name: 'Product'
belongs_to :request_product, class_name: 'Product'
end
我假设多个用户可以与多个产品相关联。给你:
user.products
product.user
request.requester # will return the relevant requesting user
request.requestee # will return the relevant requestee user
request.requester_product # will return the relevant requesting user's product
request.requestee_product # will return the relevant requestee user's product
product.requests # all requests associated to a product
user.requests # all requests associated to a user