associations - Left outer join a nested select in Rails -


i'm trying set classic 'like' model posts on blog, users can create 1 post. have following models:

class post < applicationrecord   belongs_to :user   has_many :likes end  class user < applicationrecord   has_many :posts   has_many :likes end  class < applicationrecord   belongs_to :user   belongs_to :post, counter_cache: true end 

in controller monitor logged in user, current_user.

i add column posts model indicates whether or not current_user has liked each post.

i tried adding method posts model looks likes:

class post < applicationrecord   belongs_to :user   has_many :likes   def user_liked     !likes.empty?   end end 

and using includes in controller method.

@posts = post.includes(likes: { user: current_user }).where(safe_params).order(order) render json: @posts 

however following error:

argumenterror (#<user id: 1, username: "pete", ... > not recognized preload): app/controllers/posts_controller.rb:51:in `index' 

i'm using rails api 5.0.


update:

to clarify, i'm looking rails equivalent of sql statement:

select *  posts left outer join     (select *       likes      likes.user_id = current_user.id) mylikes on posts.id = mylikes.post_id 

the problem includes takes name of associations parameters (like :user, :likes, :posts) parameter , not include instances(in case current_user)

you try following instead.

@posts = post.includes(likes: :user).where(safe_params).order(order) 

if want check if posts belong current_user or not (in haml view example)

- @posts.each |post|   - if post.likes && post.likes.any? { |like| like.user_id == current_user.id }      %span have commented on post 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -