Associated models in Rails?

Posted by dannymcc on Stack Overflow See other posts from Stack Overflow or by dannymcc
Published on 2010-06-07T09:27:12Z Indexed on 2010/06/07 9:32 UTC
Read the original article Hit count: 313

Hi Everyone,

In my rails application I have two models called Kases and Notes. They work in the same way comments do with blog posts, I.e. each Kase entry can have multiple notes attached to it.

I have got everything working, but for some reason I cannot get the destroy link to work for the Notes. I think I am overlooking something that is different with associated models to standard models.

Notes Controller

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

Kase Model

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

Note Model

class Note < ActiveRecord::Base
  belongs_to :kase
end

In the Kase show view I call a partial within /notes called _notes.html.erb:

Kase Show View

<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 %>

As you can see, I have a Remove Note destroy link, but that destroys the entire Kase the note is associated with. How do I make the destroy link remove only the note?

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

Any help would, as always, be greatly appreciated!

Thanks,

Danny

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about link