2013-05-10 20 views
0

新設計。我正在使用部分表單發表評論。我想知道如何將當前用戶傳遞給表單。這樣我就可以用它來顯示用戶發佈了什麼評論。我試着做類似current_user => current_user.name但得到一個未定義的本地變量,因爲沒有範圍內的用戶實例。有什麼建議麼?使用設計寶石,我如何顯示用戶名和評論?

<%= form_for Comment.new(:party_id => party.id), :remote => :true do |f| %> 
      <div class="field"> 
       <%= f.hidden_field :party_id %> 
      </div> 

      <div class="field"> 
       <%= f.text_area :body %> 
      </div> 

      <div class="field"> 
       <%= f.submit %> 
      </div> 
<% end %> 

回答

3

設計提供view helpers。因此,這應該是足夠

<%= current_user.name %> 
+0

<%= current_user.name %> <%= comment.body %>
我已將它添加到我的評論中,但名稱仍然沒有讓步。我是否需要在我的評論表單中聲明它? – Dap 2013-05-10 21:09:07

+0

謝謝你的工作,我注意到我沒有提交名稱屬性。 – Dap 2013-05-12 18:17:10

1

即使你添加爲隱藏字段,將用戶仍然能夠改變他們與形式發送,如果他們檢查HTML代碼的值。您應該在控制器操作中執行此操作。我也認爲這會更好,而不僅僅是一個名字。

# in Comment model 
class Comment < ActiveRecord::Base 
    belongs_to :user 
    ... 

# in User model 
class User < ActiveRecord::Base 
    has_many :comments 
    ... 

# in CommentsController 
def create 
    @comment = current_user.comments.build(params[:comment]) # current_user is a devise helper method 
    if @comment.save 
    ...