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

6
  • Have you restarted your development server?
    – Romuloux
    Feb 5, 2020 at 17:24
  • yes, same error occurs Feb 5, 2020 at 17:25
  • Can you show the console commands (input and output) you use when it does work please?
    – Romuloux
    Feb 5, 2020 at 17:37
  • 1
    Sure, I have edited my post to include a picture of the console. Feb 5, 2020 at 17:41
  • Thanks, as an aside, that console output might include your email. I would think about maybe cropping it.
    – Romuloux
    Feb 5, 2020 at 17:51

1 Answer 1

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.

3
  • Sorry, a bit new to Solidus/Ruby on Rails. Where should I add in the code you suggested? Feb 5, 2020 at 17:51
  • That answer can be found in the spree docs: guides.spreecommerce.org/developer/customization/logic.html. but this would go in app/models/spree/user_decorator.rb
    – Romuloux
    Feb 5, 2020 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. Feb 5, 2020 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.