Home>

I want to list the portfolios I like

Corresponding source code
Table design
Users table
      t.string: nickname, null: false
      t.string: email, null: false, default: ""
      t.string: encrypted_password, null: false, default: ""
   portfolios table
T.string: name, null: false
      t.string: link, null: false
      t.text: description, null: false
T.integer: likes_count
      t.references: user, null: false, foreignkey: true
   Likes table
      t.references: user, foreignkey: true
      t.references: portfolio, foreignkey: true
Association
User model
Has_many: portfolios, dependent :: destroy
 Has_many: like_portfolios, through:: likes, source :: portfolio
 Has_many: likes, dependent :: destroy
Portfolio model
Belongs_to: user
  Has_one_attached: image
  Has_many: likes, dependent :: destroy
  Has_many: liking_users, through:: likes, source:: user
   like model
Belongs_to: portfolio, counter_cache:: likes_count
 Belongs_to: user
What I tried
portfolios_contoroller.rb
  def favorite
    @portfolios = current_user.likes.all
  end


I tried as above, but the link column of portfolio cannot be retrieved, and it becomes an undefined method.

Supplementary information (FW/tool version, etc.)

rails 6.0.0
devise (user registration function)
Mysql

  • Answer # 1

    def favorite
        likes = Like.find_by (user_id: current_user.id)
        if likes.present?
        @portfolios = Portfolio.all.where (id: likes.portfolio_id)
        end
      end


    Now you can list the things that the logged-in user likes.

  • Answer # 2

    To be honest, I'm not sure what I want to do ...

    @portfoliosEven though it is a variable name, what I am getting islikesIt has become

    For example, if you want to get one link of the logged-in user's portfolio, you should write:

    current_user.portfolios.first.link