2016-02-13 45 views
1

我只在user_id等於用戶的帖子時嘗試呈現表單。這樣,無論何時用戶試圖訪問另一個配置文件,表單都不會顯示出來。如果user_id等於用戶的帖子,則呈現表格

這對渲染當前代碼:

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

它並不隱藏窗體時,我嘗試訪問其他的個人資料,所以我試圖做的每一個循環,它的工作,但有一個小bug。如果用戶還沒有任何帖子,表格根本不會顯示。

的每個循環:

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

Posts控制器:

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:我提出在縱斷面圖和不是索引的呈現形式。 資料控制器:

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 

回答

0

當然,你應該評估@user.id是否相同current_user

#app/views/profiles/show.html.erb 
<%= render "posts/form" if current_user.id == @user.id %> 

#app/controllers/profile_controller.rb 
class ProfileController < ApplicationController 
    def show 
     @user = User.find params[:id] 
     @posts = @user.posts 
     @post = @posts.new 
    end 
end 

這種類型的功能被稱爲authorization,這意味着你會使用CanCanCan更好地使其更有效地工作:

#Gemfile 
gem "cancancan" 

#app/models/ability.rb 
class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 
    can :manage, Post, user_id: user.id 
    end 
end 

#app/views/profiles/show.html.erb 
<%= render "posts/form" if can? :create, @post %> 

以上工作應考慮@post將有@user.id,而不是current_user.id作爲其外鍵。

+0

未定義的方法'can?' – Raymond

+0

您是否添加了cancancan gem? –

+0

是的,並且安裝了該軟件包 – Raymond