Rails 5 API passing a controller varible to the model -
i'm trying create column in 1 of models uses requesting user's id generate column. current user request header:
# app/controllers/posts_controller.rb if request.headers['authorization'] token_string = request.headers['authorization'] current_user = user.where(token: token_string).take end
i create method in model uses current_user
:
# app/models/post.rb attr_accessor :user_voted def user_voted(current_user) if current_user return postvote.where(post_id: self[:id], user_id: current_user[:id]).size > 0 else return false end end
before rendering in controller do:
@articles = article.where(safe_params) .order(order) .limit(10) .offset(offset) @articles.user_voted current_user
i following error when try run this:
nomethoderror (undefined method `user_voted' #<post::activerecord_relation:0x00000003b8fbe8>): app/controllers/posts_controller.rb:55:in `index'
what proper way pass controller information model?
@articles
instance of post::activerecord_relation
, , not instance of post
. have incorporate current_user
where
clause in controller.
@articles = article.where(safe_params) .order(order) .limit(10) .offset(offset) @did_user_vote = @articles.joins(:post_votes) .where(post_votes: { user_id: current_user.id }) .exists?
so join post_votes
relation in @articles
query, , posts have postvotes
user.
Comments
Post a Comment