2011-11-24 56 views
1

我有一個問題模型和一個評論模型。在問題#show view中,我有一個評論表單。我在問題#show controller動作中爲表單創建了@comment,然後將它傳遞給註釋#create controller action以實際創建並將註釋保存到數據庫。但是,一旦@comment參數傳遞給comment#create動作,我不再擁有需要的issue_id信息。我將如何傳遞這些信息?下面是我的文件:如何將參數從form_for傳遞到其他控制器?

<%= form_for @comment do |f| %> 
    <%= render 'comment_fields', :f => f %> 
    <%= f.submit "Submit" %> 
<% end %> 

問題控制器:

def show 
    @issue = Issue.find(params[:id]) 
    @votes = Votership.where(:issue_id => @issue.id) 
    @current_user_vote = @votes.where(:user_id => current_user.id).first 
    @comment = Comment.new 
    end 

和評論控制器:

def create 
    @comment = Comment.new(params[:comment]) 
    @comment.save 
    redirect_to :back 
    end 

回答

0

你只需要修改你的show行動

創建 @comment方式
def show 
    @issue = Issue.find(params[:id]) 
    @votes = Votership.where(:issue_id => @issue.id) 
    @current_user_vote = @votes.where(:user_id => current_user.id).first 
    @comment = @issue.comments.build # assigns issue_id to comment 
end 

現在,當您呈現形式@commentissue_id應該是存在於隱藏的表單輸入


這無關你的問題,但我也注意到你正在加載@current_user_vote

方式
@current_user_vote = @votes.where(:user_id => current_user.id).first 

你或許應該這樣做,因爲:

@current_user_vote = current_user.votes.first 
+0

我通過創建問題#show view的註釋來嘗試這樣的事情,它包含我需要的正確變量。然而,當它傳遞給註釋#create操作時,當我做了Comment.new(params [:comment])它刪除了該變量(我相信因爲它創建了一個新的註釋並且在params中沒有包含該變量[ :評論])。當我嘗試你的代碼時,build_comment給了我一個錯誤:未定義的方法'build_comment' –

+0

您使用的是哪個版本的Rails?我更新了我的答案。 –

+0

版本3.1 ...我需要的是一種將issue_id傳遞給我的評論控制器的方法。我幾乎通過傳遞隱藏字段來實現它的工作,就像這樣:<%= hidden_​​field(:issue_id,@ issue.id)%>然而,我不認爲我實現了這個權利,因爲它傳遞了一個叫做issue_id key = @ issue.id和value = nil。 –

0

如果我沒理解好,一n問題可能有很多評論和評論屬於一個問題?

# config/routes.rb 
# Nest the comment under the issue 
resources :issues do 
    resources :comments, only[:create] 
end 

# app/models/issue.rb 
has_many :comments 

# app/models/comment.rb 
belongs_to :issue 

# app/controllers/issues_controller.rb 
def show 
    @issue = Issue.find params[:id] 
    ... 
end 

# app/views/issues/show.html.erb 
<%= form_for [@issue, @issue.comments.build] do |f| %> 
.... 
<% end %> 

# app/controllers/comments_controller.rb 
def create 
    @issue = Issue.find params[:issue_id] 
    @comment = @issue.comments.build params[:comment] 
    if @comment.save 
    redirect_to @issue 
    else 
    render 'issues/show' # => it will know which issue you are talking about, don't worry 
    end 
end 

# or if you don't need validation on comment: 
def create 
    @issue = Issue.find params[:issue_id] 
    @issue.comments.create params[:comment] 
    redirect_to @issue 
end 

問題#顯示有點奇怪。

def show 
    @issue = Issue.find params[:id] 
    @votes = @issue.voterships 
    @current_user_vote = current_user.votes.first 
    # maybe you want to list all the comments: @comments = @issue.comments 
end 
+0

是的,但我沒有註釋資源......這是不需要的。這不起作用 –

+0

我加入了一個資源。但是,評論屬於應用程序的問題。所以有一個雙重嵌套的資源。在那種情況下我會怎麼做? –

+0

但我如何使用您建議的其他代碼知道我需要app/issue/comment –

相關問題