Rails: Passing new child object placeholder (build) to parent view
Posted
by
Meltemi
on Stack Overflow
See other posts from Stack Overflow
or by Meltemi
Published on 2010-12-30T02:13:57Z
Indexed on
2011/01/13
21:54 UTC
Read the original article
Hit count: 411
ruby-on-rails
|mvc
I've got 2 classes of objects... Magician has_many Rabbits
and Rabbit belongs_to Magician
.
When viewing a Magician (show.html
) I'd like to list all the associated Rabbits and then have some blank fields with a submit button to add a new Rabbit. To do so I build a new rabbit (associated to the current magician) in the Magician's show
method (below).
Edit2: found way to make it work but not sure if it's the "Rails way"?
see comments inline (below):
If I build the rabbit in Magician's show
method then when show
is rendered an empty (and invalid) rabbit ends the list before the new rabbit form fields are then shown.
If I build it in the view itself then everything works & renders correctly. I was led to believe that we should not be doing this type of stuff in the view...if so, what's the proper way to address this?
#/app/controllers/magicians_controller.rb
class MagiciansController < ApplicationController
respond_to :html, :json
def show
@magician = Magician.find(params[:id])
@rabbit = @magician.rabbits.build # <=== build here and empty rabbit gets
# included in @magician.rabbits when they're rendered...
# but is NOT included in @magician.rabbits.count for some reason?!?!?
respond_with(@magician)
end
...
end
#view/magicians/show.html.haml
%p
%b Name:
= @magician.name
%h2 Rabbits
= "There are #{pluralize(@magician.rabbits.count, "rabbit")}"
= render @magician.rabbits, :target => @magician
%h2 Add a rabbit:
- @rabbit = @clown.rabbits.build -# <=== build here and everything SEEMS to work
= render :partial =>"rabbits/form", :locals => { :parent => @magician, :foreign_key => :magician_id, :flash => flash }
Edit1: Adding generated html from partial as per request:
<p>
<b>Rabbit:</b>
<b>Color:</b>
|
<b>ID:</b>
<a href="/magicians/2/rabbits" data-confirm="Sure? A bunny will die" data-method="delete" rel="nofollow">Kill Rabbit</a>
</p>
And I suppose you probably want to see the partial that generates this:
%p
%b Rabbit:
= rabbit.name
%b Color:
= rabbit.color
|
%b ID:
= rabbit.id
= link_to("Kill Rabbit", [target, rabbit], :method => :delete, :confirm => "Sure? A bunny will die")
© Stack Overflow or respective owner