开发者

Association using has_many :through problem

开发者 https://www.devze.com 2023-03-17 08:03 出处:网络
I have an application which has two models products and purchases. Products contains a list of all products in my system and purchases define all the purchases made by us开发者_运维问答ers...

I have an application which has two models products and purchases.

Products contains a list of all products in my system and purchases define all the purchases made by us开发者_运维问答ers...

now i have a particular current_user who can view products and buy products and wen he hits buy button , he shuld b able to see all the purchases he made. i have made a association has_many :through and have created a new model named purchased_products which links the purchase and products table together..

class Product < ActiveRecord::Base
  has_many :purchased_products
  has_many :purchases, :through => :purchase_products
end

class Purchase < ActiveRecord::Base
  has_many :products, :through => :purchased_products
  has_many :purchased_products
end

class PurchasedProducts < ActiveRecord::Base
  belongs_to :purchases
  belongs_to :products
end

now I'm not getting how do i find out which user has purchased which product and show all his purchases?

Also where do i specify the code to find out all purchases of current user?


You can access a Product's Purchases and vise-versa with two very simple statements like so:

some_product = Product.find(some_product_id_or_find_query).purchases
some_purchases = Purchase.find(some_purchase_id_or_find_query).products

You have not defined the relationship between the User and any Purchase, I assume this is going to be another HABTM association so you can then access them just like you can with Product->Purchases and Purchases->Product.

You should definitely search around Google for this sort of thing as ActiveRecord associations are very well documented, http://edgeguides.rubyonrails.org/association_basics.html


If the a User has_many products and purchases, then you would reference them like, probably in you users_controller show action:

@current_user = User.find(params[:id])
@products     = @current_user.products
@purchases    = @current_user.purchases
0

精彩评论

暂无评论...
验证码 换一张
取 消