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: 258

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 }


Kase Model

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

Note Model

class Note < ActiveRecord::Base
  belongs_to :kase

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

Kase Show View

<div id="notes">    

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


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

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

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



© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about link