user1087943
user1087943

Reputation: 499

Rails current_user association by user_id

I've got three models: user, product and order. The associations are as follows:

a User (seller) has many Products

a User (buyer) has many Orders

an Order has one Product

an Order has one User (buyer)

a Product has one User (seller)

a Product has one Order

Now in the product model there's an association to a user:

belongs_to :seller, class_name: "User", foreign_key: "seller_id"

in the products_controller for adding a new product linking it to a user:

def create
  @product = current_user.products.create(product_params)
  ....

In the database the foreign key has also been renamed to "seller_id". When the current_user.products line is called the response fails

ActiveRecord::UnknownAttributeError (unknown attribute 'user_id' for Product.):
  app/controllers/products_controller.rb:23:in `create'

I'm not sure how to change the current_user to products association to use this seller_id key. Any help would be much appreciated, thanks.

Upvotes: 1

Views: 517

Answers (1)

smathy
smathy

Reputation: 27961

The :foreign_key option you have in your Product.belongs_to actually needs to be over on User.has_many, ie., in User:

has_many :products, foreign_key: :seller_id

Upvotes: 2

Related Questions