2010-06-07 100 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