2017-02-16 71 views
0

我讓用戶使用回形針上傳照片,但照片中沒有所有權。這意味着,我不知道誰上傳了照片。rails user_id添加到圖片

在這裏,我想當有人上傳圖片時,您知道哪位用戶上傳了圖片。我有一個user_id列。但我不知道如何在圖片控制器中實現代碼

我該怎麼做?謝謝!

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顯示 @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

你可以請包括你的用戶和Pic模型 - 所以我可以看到你是如何創建數據庫中的兩個實體之間的關聯。 – JayJay

回答

0

如果在上傳過程中可以識別用戶,則可以嘗試在上傳過程中在隱藏字段中傳遞user_id。你說你已經創建了user_id列。

<%= f.hidden_field :user_id , value: @user.id %> 

要使用此代碼,您需要在控制器操作中找到@user。類似於您在「索引」操作中所做的操作:通過以下方式查找用戶:user_id 如果您對用戶使用devise,則可以使用current_user.id代替。