我有两类对象...... Magician has_many Rabbits
和Rabbit belongs_to Magician
。
查看魔术师(show.html
)时,我想列出所有相关的兔子,然后有一些空白字段和提交按钮以添加新的兔子。为此,我在魔术师的show
方法(下方)中构建一只新兔子(与当前魔术师相关联)。
编辑2:找到方法让它运作但不确定它是否是" Rails方式"?
查看评论内联(下方):
如果我使用魔术师的show
方法构建兔子,那么当show
呈现为空(并且无效)时,兔子会在显示新的兔子表单字段之前结束列表。
如果我在视图中构建它,那么一切正常并且正确渲染。我被引导相信我们应该不在视图中做这种类型的东西......如果是这样,什么是解决这个问题的正确方法?
#/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 }
编辑1:根据请求从部分添加生成的html:
<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>
我想你可能想看到产生这个的部分:
%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")