2015-05-19 25 views
0

每個用戶has_many:通知,並且每個通知has_many:comments,每個通知類。每條通知/評論has_one:複審通知,正在進行評論的通知。 我在嘗試提交評論時收到此錯誤消息:undefined method 'id' for "#<Notice:0x0000010eed6958>":String。爲什麼Rails認爲我的NoticeStringRails:undefined方法`id'

notices_controller.rb:

def create 
    @notice = user.notices.build(notice_params) 
    if @notice.save 
    if !params[:notice][:commentee].nil? 
     @notice.create_comment(params[:notice][:commentee]) 
    end 
    end 
end 

private 
    def notice_params 
    params.require(:notice).permit(:content, :comentee) 
    end 

notice.rb:

belongs_to :user 
has_one :active_comment_relationship, class_name: "Commentrelationship", foreign_key: "commenter_id", dependent: :destroy 
has_one :supernotice, through: :active_comment_relationship, source: :commentee 

def create_comment(other_notice) 
    active_comment_relationship.create(commentee_id: other_notice.id) 
end 

要在通知提交評論中_notice.html.erb:

<%= form_tag({controller: "notices", action: "create"}, method: "post", id: "comment_form") do %> 
    <%= hidden_field_tag :callsign, @user.callsign %> 
    <%= hidden_field_tag "notice[commentee]", notice %> 
    <%= text_area_tag "notice[content]", '', id: "commentField" %> 
    <%= submit_tag "Reply" %> 
    <% end %> 

服務器日誌:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "callsign"=>"bazzer", "notice"=>{"commentee"=>"#<Notice:0x00000110a49140>", "content"=>"Hello there."}, "commit"=>"Reply"} 
+0

您不能在參數'<%= hidden_​​field_tag>通知[commentee]「中註冊對象,注意%>','」commentee「=>」#<注意:0x00000110a49140>',它會變成字符串。 – roxxypoxxy

回答

0

因爲它只能以表單值的形式呈現爲字符串。序列化來回也不會對你有任何好處。顯而易見的選擇是傳遞該通知的id並查找它。但我個人更喜歡有點不同的做法。

如果評論發佈該通知的show頁面上你可能不需要從表單傳遞notice_id都::id已經存在的路線的一部分。如果你製作一個嵌套資源:

resources :notices do 
    resources :comments 
end 

......你的評論的路線貼在通知的路線上。你可以做一個控制器的意見和評論的收集可以用類似的路線進行訪問:

notices_comments_path(@notice) 
# => /notices/42/comments 

所以,當你郵寄到上述格式的URL評論,您必須在通過沒有任何隱藏的在所有 PARAMS:

  • Commentee可以從給定的params[:note_id]在路由中查找
  • callsign可以在控制器鋪地擡頭對current_user ER(帶有設計或法術)

而要做到這一切的原因是因爲隱藏輸入從視線中隱藏起來,而不是從開發工具和開放篡改是這樣。爲了解決這個問題,在控制器中使用額外的檢查是很誘人的,但是爲什麼如果他的控制器能夠自己分配它們呢?

反模式警告:不要過多地嵌套資源。 2級可以,3級關注,4級可怕。