2010-06-07 105 views
0

在我的rails應用程序中,我有兩個模型叫做Kases和Notes。他們以與博客文章評論相同的方式工作,即I.e.每個Kase條目可以附加多個註釋。Rails中的相關模型?

我已經得到了一切正常,但由於某種原因,我無法獲得破壞鏈接爲Notes工作。我認爲我忽視了與標準模型相關的模型有所不同。

注意控制器

class NotesController < ApplicationController 
    # POST /notes 
    # POST /notes.xml 
    def create 
    @kase = Kase.find(params[:kase_id]) 
    @note = @kase.notes.create!(params[:note]) 
    respond_to do |format| 
     format.html { redirect_to @kase } 
     format.js 
    end 
    end 

end 

加瀨型號

class Kase < ActiveRecord::Base 
    validates_presence_of :jobno 
    has_many :notes 

注意型號

class Note < ActiveRecord::Base 
    belongs_to :kase 
end 

在加瀨秀鑑於我打電話/ Notes中的部分稱爲_notes.html.erb:

加瀨顯示視圖

<div id="notes">  

     <h2>Notes</h2> 
      <%= render :partial => @kase.notes %> 
      <% form_for [@kase, Note.new] do |f| %> 
       <p> 
        <h3>Add a new note</h3> 
        <%= f.text_field :body %><%= f.submit "Add Note" %> 
       </p> 
      <% end %> 
    </div> 

/notes/_note.html.erb

<% div_for note do %> 
<div id="sub-notes"> 
    <p> 
    <%= h(note.body) %><br /> 
    <span style="font-size:smaller">Created <%= time_ago_in_words(note.created_at) %> ago on <%= note.created_at %></span> 
    </p> 

<%= link_to "Remove Note", kase_path(@kase), :confirm => 'Are you sure?', :method => :delete, :class => 'important' %> 

</div> 
<% end %> 

正如你可以看到,我有一個刪除註釋銷燬鏈接,但是破壞了該註釋關聯的整個Kase。我如何使銷燬鏈接只刪除筆記?

<%= link_to "Remove Note", kase_path(@kase), :confirm => 'Are you sure?', :method => :delete, :class => 'important' %> 

任何幫助將一如既往,非常感謝!

感謝,

丹尼

回答

1
<%= link_to "Remove Note", note_path(note), :confirm => 'Are you sure?', :method => :delete, :class => 'important' %> 

,你還需要在配置/ routes.rb中以下條目(檢查是否已經存在)

map.resources :notes 

,檢查下面的方法在您的NotesController中

def destroy 
    @note = Note.find(params[:id]) 
    @note.destroy 
    .... # some other code here 
end 

有同樣表現的另一種方式,如果你沒有一個NotesController,不想把它

+0

太棒了,這是我錯過的map.resources。 Woops! 謝謝! – dannymcc 2010-06-07 09:39:25

1

你調用一個加瀨-t帽子就是爲什麼它刪除加瀨刪除方法。有沒有在這個環節

<%= link_to "Remove Note", kase_path(@kase), :confirm => 'Are you sure?', :method => :delete, :class => 'important' %> 
從甚至提到的說明文字

分開 - 那麼,爲什麼它刪除便箋?嘗試

<%= link_to "Remove Note", note_path(note), :confirm => 'Are you sure?', :method => :delete, :class => 'important' %> 

這假定您已設置了標準的寧靜路線和操作。

作爲一個額外的點,你永遠不應該使用非獲得的link_to行動,因爲

  1. 谷歌的蜘蛛之類的意志 點擊它們。你可能會說'他們 不能,因爲你需要在'登錄 '這是真的,但它仍然是 不是一個好主意。
  2. 如果有人試圖 在新標籤/窗口 打開鏈接它會破壞你的網站,或去 錯誤的頁面,因爲它會嘗試 打開該網址,但與得到,而不是刪除的 。
  3. 一般,在網頁 設計,鏈接應該帶你 某處,按鈕應該'做 東西',即進行更改。 A 這樣的破壞性行爲 因此屬於按鈕而不是 鏈接。

改爲使用button_to,它構造一個表單來做同樣的事情。
http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M002420&name=button_to

+0

link_to with:method =>:delete OR:confirm set也會創建一個

標記,因此可以安全使用 – 2010-06-07 09:40:46

+0

我並不知道button_to選項是誠實的! 感謝您的回答,我知道我沒有在這裏發佈的鏈接中引用註釋 - 我已經嘗試了一些不同的變體,並且即使它沒有執行所需的操作,它也是做了某件事情*。 再次感謝! – dannymcc 2010-06-07 09:55:04