我有一个部分现在看起来像这样:
<%= render(:partial => 'order', :object => Order.new %>如何将一些空的LineItem对象构建到Order.new中,如:object => Order.new中所示?
请注意Order has_many :line_items。和LineItem belongs_to :订单
正如一位评论者提到的,这一开始似乎违反了MVC的设计,但我忘了提到,这个呈现实际上是在一个link_to_function助手中,它用于动态地插入属性行项目的更多字段。
实际的帮助器如下所示:
#orders_helper.rb
def add_line_item_link(name, form_scope)
link_to_function name, :class => "add_line_item_link" do |page|
line_item_html = render(:partial => 'line_item', :object => @order.line_items.new, :locals => {:f => form_scope})
page << %{
var time_index = new Date().getTime();
var line_item_html = #{line_item_html.to_json};
line_item_html = line_item_html.replace(/_\\d+/g, "_"+time_index);
line_item_html = line_item_html.replace(/\\[\\d+\\]/g, "\\["+time_index+"\\]");
$('line_items').insert({bottom: line_item_html});
}
end
end@order.line_items.new是我喜欢做的事情:
首先:我希望在@order对象中不是只构建一个line_item,而是三个。第二:行项目有一个名为' title‘的属性,每当我们收到订单时,几乎每次订单都有三个行项目,一个有标题编辑器,一个有标题摄影师,还有一个有标题视频编辑器。
所以我想,也许我可以这样做:
#orders_controller.rb
@titles = %w(editor photographer video-editor)
#orders_helper.rb
...#same as above
:partial => 'line_items', :collection => lambda { @titles.each {|t| @order.line_items.build(:title => t) } return @order.line_items}
...有什么建议吗?谢谢
发布于 2009-12-11 13:21:05
在回答您更改的问题时--
#order.rb
def default_line_items
self.line_items.build(:title => "editor")
self.line_items.build(:title => "photographer")
self.line_items.build(:title => "video_editor")
return self.line_items
end
#call to partial
render (:partial => "line_item", :collection => order.default_line_items)发布于 2009-12-12 11:49:05
重构Matt的答案:
def default_line_items
line_items.build %w(editor photographer video_editor).collect { |i| {:title => i } }
end一句话。做同样的事情。
发布于 2009-12-11 13:27:18
我很抱歉,但这对我来说是一个严重的代码味道。违反MVC原则。视图层不应该与模型层有任何直接的交互。
https://stackoverflow.com/questions/1885418
复制相似问题