我只是在user_id等于用户的帖子时才尝试呈现表单。因此,每当用户尝试访问另一个配置文件时,表单都不会显示。
这是渲染的当前代码:
<% if current_user.id == @post.user_id %>
<%= render 'posts/form' %>
<% end %>
每当我尝试访问另一个配置文件时它都不会隐藏表单,所以我尝试了每个循环并且它有效,但有一个小错误。如果用户尚未发布任何帖子,则表单根本不会显示。
每个循环:
<% @posts.take(1).each do |p| %>
<% if current_user.id == p.user_id %>
<%= render 'posts/form' %>
<% end %>
<% end %>
帖子控制器:
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 :(得分: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
作为其外键,上述情况应该有效。