1
votes

I want to use callbacks to modify the admin product controller to create a listing for each user. Using decorator in spree product model I added the "belongs_to :user" relation. In my custom user model I added the "has_many :products" relation and also added product_id and index product_id to my user data table. I have this:

Spree::Admin::ProductsController.class_eval do
create.before :user_products

private

 def user_products
    @user.objects.build params[object_name]
 end
end 

object_name is a function inherited from ResourceController. It returns a string containing current object name “product”.

But it is not working. I am getting "undefined method objects for User XXXXX" Looks like my association is not working. What am I doing wrong? Thanks in advance.

1
What is name of your custom model and relationship with user and product? - Vishal G
My custom model is called User. In user model I have: has_many products, class_name: 'Spree::Product' In Spree product model I have: if Spree.user_class belongs_to :user, class_name: Spree.user_class.to_s else belongs_to :user - aminhs
Yes your association is wrong user_id should be there in spree_products table instead of product_id in user's table - Vishal G
Why? I am not creating many to many relationship. I have product_id in user table. So do you think I should remove product_id from user and add user_id in spree_product table? - aminhs
yes it is has_many relation with products, many to many you need join table or has_thorugh association - Vishal G

1 Answers

0
votes

Your foreign key is wrong it should be like this

class User < ActiveRecord::Base
  has_many :products
end

Class Product < ActiveRecord::Base
  belongs_to :user
end

Products table should have user_id

here is reference http://guides.rubyonrails.org/association_basics.html#the-has-many-association

enter image description here