我允许用户使用回形针上传照片,但照片中没有所有权。这意味着,我根本不知道是谁上传了这些照片。
在这里,我想当有人上传图片时你知道哪个用户上传了它。我有一个user_id列。但我不知道如何在pic控制器中实现代码
我该怎么做?谢谢!
class PicsController < ApplicationController
before_action :find_pic, only: [:show, :edit, :update, :destroy]
def index
@user = User.find( params[:user_id])
@pics = Pic.all.order("created_at DESC")
end
def show
end
def new
@pic = Pic.new
end
def create
@pic.user = current_user
@pic = Pic.new(pic_params)
if @pic.save
redirect_to @pic, notice: "Yes it was posted"
else
render 'new'
end
end
def edit
@user = User.find(params[:user_id])
@profile = @user.profile
end
def update
if @pic.update(pic_params)
redirect_to @pic, notice: "Congrates Pic was upaded"
else
render 'new'
end
end
def destroy
@pic.destroy
redirect_to users_path
end
private
def pic_params
params.require(:pic).permit(:title, :description, :profile_id)
end
def find_pic
@pic = Pic.find(params[:id])
end
端
class UsersController < ApplicationController
before_action :authenticate_user!
def index
@pics = Pic.all.order("created_at DESC")
end
def show
@user = User.find(params [:id])
@pics = User.find_by(user_name:params [:user_name])
端
端
class ProfilesController < ApplicationController
before_action :authenticate_user!
before_action :only_current_user
def new
@user = User.find( params[:user_id])
@profile = Profile.new
end
def create
@user = User.find(params[:user_id])
@profile = @user.build_profile(profile_params)
if @profile.save
redirect_to user_path( params[:user_id])
else
render action: :new
end
end
def edit
@user = User.find(params[:user_id])
@profile = @user.profile
end
def update
@user = User.find(params[:user_id])
@profile = @user.profile
if @profile.update_attributes(profile_params)
flash[:success] = "Profile Updated"
redirect_to user_path(params[:user_id])
else
render action: :edit
end
end
private
def profile_params
params.require(:profile).permit(:avatar, :user_name, :contact_email, :description)
end
def only_current_user
@user = User.find(params[:user_id])
redirect_to(root_url) unless @user == current_user
end
端
答案 0 :(得分:0)
如果在上传过程中可以识别用户,则可以尝试在上传过程中传递 user_id in hidden_field 。你说你已经创建了user_id列。
<%= f.hidden_field :user_id , value: @user.id %>
要使此代码正常工作,您需要在控制器操作中找到@user。与您在“索引”操作中已经执行的操作类似:通过:user_id查找用户
如果您对用户使用devise
,则可以改为使用current_user.id
。