1

Trying to build a friends feature on top of a Solidus framework, but the .friends method does not work. It does in rails console, however.

SpreeUsers Controller (current_spree_user.friends causes error):

class SpreeUsersController < ApplicationController
  def my_friends
    @friendships = current_spree_user.friends
  end

  def search
    @spree_users = SpreeUser.search(params[:search_param])
    render json: @spree_users
  end
end

Friendship Model:

class Friendship < ActiveRecord::Base
  belongs_to :spree_user
  belongs_to :friend, :class_name => 'SpreeUser'
end

SpreeUser Model:

class SpreeUser < ActiveRecord::Base
  has_many :friendships
  has_many :friends, through: :friendships
end

Error: undefined method `friends' for # Did you mean? friendly_id?

https://i.stack.imgur.com/u4F8K.png

Console Input/Output:

https://i.stack.imgur.com/YuVjb.png

1 Answers1

0

I believe I know what is happening here.

You have declared a model SpreeUser with a friends relationship. This is why in your console it works. You are correctly calling the friends method on the class SpreeUser.

The error you are receiving is for the class Spree::User (Note the different class names). I am assuming you are using spree_auth_devise which provides that class.

You will need to properly add your logic from SpreeUser to Spree::User. I believe Spree/Solidus recommends doing so using decorators.

EG

Spree::User.class_eval do

    has_many :friendships
    has_many :friends, through: :friendships

end

Above not tested and a best guess taken from this SO answer

You could also test my theory by running Spree::User.first.friends in your console. You should receive a similar error to the browser.

Romuloux
  • 1,027
  • 1
  • 8
  • 24
  • Sorry, a bit new to Solidus/Ruby on Rails. Where should I add in the code you suggested? – binniebraces Feb 05 '20 at 17:51
  • That answer can be found in the spree docs: https://guides.spreecommerce.org/developer/customization/logic.html. but this would go in `app/models/spree/user_decorator.rb` – Romuloux Feb 05 '20 at 17:52
  • So I made the new folder spree in models and created the the user_decorator.rb file with the code you specified, but the same error occurs. – binniebraces Feb 05 '20 at 18:01