Home>

I want to write a conditional if statement in a view in the controller.

Code
<% @ posts.each do | post |%>
  <% if post.user.id! = @ current_user.id&&post.user.status == 2%>
  <% else%>
    <% = post.name%>
  <% end%>


An if statement that post's user.id is not a logged-in user and post holder status is 2

def user
    return User.find_by (id: self.user_id)
end
def index
    user = User.find_by (id: self.user_id)
    @ mypostpost.user.id! = @ current_user.id
    @pstatus = Post.where.user (status: 2)
    @posts = Post.all.order (created_at:: desc) .where.not (id: @ mypost.id, id: @ pstatus.id)
end
Error
undefined method `user_id 'for #<PostsController: 0x00007fba5e431b40>Did you mean? user_url


An error occurs because the def user described in model is not reflected in the controller.
Also, I tried to describe it in the controller, but no response was obtained.

  • Answer # 1

    model defines user and the error is user_id.

    "If statement conditional branching in the view is described in the controller" means that @posts passed to the view is "post user is not a login user and post holder status is not 2" I want to narrow down to
    Does that mean

    First, user, user.id and user_id are confused. There is a caution.

    @posts = Post.joins (: user).   where.not (users: {id: current_user.id}).   where (users: {status: 2}). Order (created_at:: desc)
    I think that's Kana

    @ mypostpost.user.id! = @ current_user.id
    @pstatus = Post.where.user (status: 2)
    I don't understand the part, so the latter condition where.not (id: @ mypost.id, id: @ pstatus.id was omitted, so add it if necessary

    Additional
    def user     return User.find_by (id: self.user_id) end
    I was worried about it.
    I think this was defined in class Post, but is it defined as belongs_to: user?
    If it is, this method is unnecessary.
    Otherwise, the above answer will not work