2012-11-27 23 views
-1

我正在嘗試遵循Ruby on Rails Twitter應用程序上的教程,但隨着我到達最後,我注意到我並不十分喜歡您可以創建其他用戶的帖子。我的願望是創造你自己的。Ruby on Rails Twitter應用程序 - 在創建新狀態時關聯當前用戶ID

我怎樣才能做到這一點

Status Controller Create: 
def create 
@status = Status.new(params[:status]) 
respond_to do |format| 
    if @status.save 
    format.html { redirect_to @status, notice: 'Status was successfully created.' } 
    format.json { render json: @status, status: :created, location: @status } 
    else 
    format.html { render action: "new" } 
    format.json { render json: @status.errors, status: :unprocessable_entity } 
    end 
end 
end 

狀態創建視圖,因爲它是目前:

... 
<div class="field"> 

<%= f.input :user_id, collection: User.all, label_method: :full_name %> 
<%= f.input :content %> 
</div> 
<div class="form-actions"> 
<%= f.submit %> 
</div> 

狀態型號:

class Status < ActiveRecord::Base 
attr_accessible :content, :user_id 
belongs_to :user 
end 

希望有人能幫助!

回答

2

你可以在這裏使用一些授權!


一個更簡單的方法來做到這一點,因爲你正在編寫一個教程(=>你想學習),你可以用關聯來解決它。

內部應用程序/模型/ user.rb

has_many :statuses, dependent: :destroy 

,並刪除attr_accessible:從應用程序/模型/ status.rb USER_ID

attr_accessible:屬性意味着用戶可以明確設置這個值屬性通過一個表單,你不想要的。

然後檢查您的控制器是否爲正在創建帖子的用戶是當前登錄的用戶。如果沒有,請不要允許。

0

如果更改此

<%= f.input :user_id, collection: User.all, label_method: :full_name %> 

(some place in you view - or in the controller) 
<% <your object>.user_id = <current user id> %> 
... 
<%= f.hidden_field :user_id %> 

我認爲它會工作

+0

感謝您的回答,但我已經嘗試過。解決方案應該在狀態控制器的創建方法 –

1

在應用控制器:

def current_user 
    User.find(session[:user_id]) if session[:uid] 
end 

你必須設置會話user_id whe你認證用戶。

您認爲(使用SimpleForm):

<%= f.input :user_id, as: :hidden, input_html: { value: current_user.id }%> 

這將工作。讓我知道如果你卡住了。

+0

謝謝!這很有效,但我設法通過添加這個來修改狀態控制器,它的工作方式和我想要的一樣:@ status.user = current_user –

+0

這也可以。還取決於您的應用程序需求(例如,如果您正在開發API功能或HTML渲染等)祝您好運並享受您對Rails的探索 – jwg2s