Marco De Rossi said over 3 years ago on Like Relationships and Global ID :
hi   
How do I scope for posts liked by a user and show them on the user's profile page?

I tried 
user.users_posts

user.liked_posts,
 
 none of them gives me the results
user.users_posts get only the id on the posts 


David Kimura PRO said over 3 years ago on Like Relationships and Global ID :
  Do you have the associations in your models?

  has_many :users_posts
  has_many :liked_posts, through: :users_posts, source: :post

You can then call user.liked_posts on your instance of the user.

Marco De Rossi said over 3 years ago on Like Relationships and Global ID :
  Thanks, I had a typo.  I have loop all users liked posts on the user profile page.  I get this error when I add the unfollow link
undefined method `to_sgid

## user_profile.html.erb
@liked_post.each do |post|%>

link_to  "Unfollow",posts_like_path(post, id: @liked_post.to_sgid(expires_in: 1.hour)),method: :delele

## users_controller

def user_profile
  @user= current_user
  @posts = @user.posts.all 
  @liked_post = @user.liked_post   
 end

This setup works fine on the post-show page but not on the user profile page

David Kimura PRO said over 3 years ago on Like Relationships and Global ID :
  you're looping through all of the liked posts, so you would need to call post.to_sgid instead of @liked_post.to_sgid

Marco De Rossi said over 3 years ago on Like Relationships and Global ID :

link_to  "Unfollow",post_like_path(post, id: post.to_sgid(expires_in: 1.hour)),method: :delete
Error referencing Posts::LikesController#destroy
PG::ForeignKeyViolation: ERROR: update or delete on table "posts" violates foreign key constraint "fk_rails_fbe88b52fa" on table "users_posts"
DETAIL: Key (id)=(10) is still referenced from table "users_posts".

def destroy    
  post = Post.friendly.find(params[:post_id])
  user_post = GlobalID::Locator.locate_signed(params[:id])
  user_post.destroy!    
  redirect_to post_path(post), alert: "unfollow"  
end

David Kimura PRO said over 3 years ago on Like Relationships and Global ID :
  It looks like we have a bit of mixed up logic here because the post.to_sgid that you're calling is the actual post, not the users_post record.

So, in your destroy action, you would need to have something like this below. This is happening likely because you're on a index action (where you're listing out all of the liked posts) instead of the show action for a particular post like in the episode.

def destroy
  post = Post.friendly.find(params[:post_id])
  user_post = UserPost.find_by(post: post, user: current_user)
  user_post.destroy!
  redirect_to post_path(post), alert: "unfollow"  
end

In this scenario, you're not really doing anything with the signed global id as it's not referring to the actual UserPost.

Login to Comment