خرید بک لینک

Vote count: 0

I am trying to render a form only if the user_id is equal to the user's post. So that whenever a user tries to visit another profile the form does not show up.

That's the current code for the rendering:

<% if current_user.id  == @post.user_id %>
    <%= render 'posts/form' %>
<% end %>

It doesn't hide the form whenever I try to visit another profile so I tried doing an each loop and it worked but with one small bug. If the user doesn't have any posts yet, the form does not appear at all.

The each loop:

<% @posts.take(1).each do |p| %>
    <% if current_user.id  == p.user_id %>
        <%= render 'posts/form' %>
    <% end %>
<% end %>

Posts controller:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @posts = Post.all
    @post = Post.new
  end


  def show

  end


  def new
    @post = current_user.posts.build
  end


  def edit
  end

  def create
    @post = current_user.posts.build(post_params)
    if @post.save
      redirect_to :back
    else
      render 'new'
    end
  end

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @post.destroy
    redirect_to :back
  end

  private
    def set_post
      @post = Post.find(params[:id])
    end

    def post_params
      params.require(:post).permit(:description)
    end
end

P.S: I made the form to render in the profile view and not the index's. Profile controller:

class ProfileController < ApplicationController
    def profile
        @posts = Post.where( "user_id = ?", User.find_by_id(params[:id]) )
        @post = Post.new
        @post = current_user.posts.build
    end
end

asked 2 mins ago

- - , .

برچسب: نویسنده: استخدام کار تاريخ: شنبه 24 بهمن 1394 ساعت: 18:24

صفحه بندی