新手问题 button_to 问题

jiwoorico · 2013年08月22日 · 最后由 jiwoorico 回复于 2013年08月22日 · 2166 次阅读
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h2>Your Pragmatic Cart</h2>
<ul>
<% @cart.line_items.each do |item| %>
<li><%= item.quantity %> &times; <%= item.product.title %></li>
<% end %>
</ul>
 <%= button_to 'Empty cart', @cart, method: :delete, confirm: 'Are you sure?' %>

<%= button_to 'Empty cart', @cart, method: :delete, confirm: 'Are you sure?' %> 这行代码里的@cart表示的是什么?我看官方文档是 button_to(name = nil, options = nil, html_options = nil, &block),还是不大明白。求解释?

这里的 @cartCart Model 的一个实例,这行代码是要删除这个 model。

#1 楼 @lgn21st 这个@cart是指 button_to(name = nil, options = nil, html_options = nil, &block) 这里的哪个参数?我看文档里没说有 instance 这个参数啊

@cart应该是从 controller 里面定义的。

这都是在 option 里面的

这里的@cart的用法,是利用 Rails 路由的resources定义去简化 URL 生成,比如这里的@cart会被展开成cart_path(@cart)这样的形式。

请参考这篇 Rails Guide http://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

#2 楼 @jiwoorico 看源码 https://github.com/rails/rails/blob/797fcdf738a2a2772544731027d4fc5ca9d358bc/actionpack/lib/action_view/helpers/url_helper.rb#L280

这行

url    = options.is_a?(String) ? options : url_for(options)

第 2 个参数如果是字符串,则把它当做 form 的 action URL,否则把他当参数传给 url_for

需要 登录 后方可回复, 如果你还没有账号请 注册新账号