2013-03-26 22 views
0

在我的Rails應用程序中,我有一個views/questions/show.html.erb頁面,除了期望的@question變量外,它還有權訪問到@answers變量來顯示特定問題的所有答案。通過表單傳遞額外的值到部分和創建動作

在顯示特定問題的所有答案的循環內部,我希望顯示一個區域供用戶評論(不是問題的答案),所以我創建了一個部分註釋,其中另一個SO回答的建議,我創建了一個'locals'散列來傳遞變量。在Comments控制器的創建操作中,我希望能夠訪問答案(評論屬於答案)和問題(has_many:答案),所以我通過在回答問題和ID到部分像這樣

<% for answer in @answers %> 
    ....(code ommitted) 
    <%= render :partial => 'comments/form', :locals => { :answer_id => answer.id, :question_id => @question.id } %> 
    ...(code ommitted) 

    <% end %> 

和我通過answer_id並通過隱藏字段中的註釋部分,像這樣

的question_id
<%= simple_form_for @comment do |f| %> 
    <%= f.input :content, as: :text, label: 'comment'%> 
    <%= f.hidden_field :user_id, :value => current_user.id %> 
    <%= f.hidden_field :answer_id, :value => answer_id %> 
    <%= f.hidden_field :question_id, :value => question_id %> 
    <%= f.button :submit %> 
    <% end %> 

在評論控制器的創建行動,我做這個

def create 
    @question = Question.find(params[:comment][:question_id]) 
    @answer = Answer.find(params[:comment][:answer_id]) 
    @comment = @answer.comments.build(params[:comment]) 
    if @comment.save 
     flash[:notice] = "Successfully created comment" 
     redirect_to root_path 
     # redirect_to question_answers_path(@question) (will eventually want to redirect to the question) 
    else 
     render :action => 'new' 
    end 
end 

第一個問題,我覺得我已經通過使提取的問題ID(和答案ID)做了一件尷尬以下列方式

@question = Question.find(params[:comment][:question_id]) 

然而,這些都是可以作爲我的提交表單的結果PARAMS

Parameters: {"utf8"=>"✓", "authenticity_token"=>"VtogfCsI137lbk2l64RXtrfRn/+Rt1/jM8pfDVY29gM=", "comment"=>{"content"=>"test", "user_id"=>"12", "answer_id"=>"25", "question_id"=>"22"}, "commit"=>"Create Comment"} 

所以我必須要挖掘出這樣的params[:comment][:question_id]

第二,更具挑戰性的問題(對我來說挑戰性)的question_id是Rails的告訴我

Can't mass-assign protected attributes: question_id 

我沒有理由來存儲question_id在評論模型上,所以我沒有在數據庫中爲它創建一個列。然而,當我做到這一點

@comment = @answer.comments.build(params[:comment]) 

因爲question_id是裏面的則params的一個:註釋(其中到了那裏由我製作的隱藏字段,它的形式),Rails正在試圖將它保存在評論表。但是,我真正想要在comments_controller.rb的create操作中訪問問題的唯一原因是在保存後使用它重定向回問題。

你能建議我能做些什麼來解決這個問題嗎?我覺得因爲我沒有很多Rails的經驗,所以我做的一切都很笨拙,這可能是它不工作的原因。我想這個問題的簡單方法是在評論模型中添加一個question_id列,但它們之間沒有「關聯」,所以我認爲這是錯誤的解決方案。

回答

0

你的第一個問題不是問題。 沒有太多的方法來做到這一點。

問題二,你必須做這樣的

@comment = @answer.comments.build(params[:comment][:content].merge(user_id: params[:comment][:user_id], answer_id: params[:comment][:answer_id])) ,否則你會嘗試分配你沒有在表中

屬性或者你可以做的另一種方式

params[:comment].delete('question_id') 

然後

@comment = @answer.comments.build(params[:comment]) 
+0

謝謝,但它不僅是:我希望保存的內容。我還需要將user_id保存在評論表中。那麼我該怎麼做呢?喜歡這個? @comment = @ answer.comments.build({params [:comment] [:content],params [:comment] [:user_id]}) – 2013-03-26 21:03:27

+0

已更新的答案! – 2013-03-26 21:05:16

+0

實際上,它還需要保存answer_id,因爲註釋belongs_to:答案模型。你能再次更新你的答案嗎?我基本上需要保存一切,除了question_id – 2013-03-26 21:08:28

相關問題