码迷,mamicode.com
首页 > 其他好文 > 详细

rails中link_to与button_to的一个功能差异

时间:2015-02-07 21:43:55      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:rails   link-to   button-to   

页面中本来设计一个按钮,功能是当按下时跳转到index方法,然后实现一段功能.关键是其中需要传递一个参数show_all,其值为true.
index方法中通过判断是否含有该参数来实现不同的逻辑,类似如下:

if params[:show_all]
      @products = Product.all
    else
      @products = Product.where("locale == ?",I18n.locale.to_s)
    end

按钮通过如下代码生成:

<%= button_to(‘show all products‘,store_index_path(show_all:true),method: :get)%>

实际生成的html代码如下:

<form class="button_to" method="get" action="/cn/store/index?show_all=true"><input type="submit" value="show all products" /></form>

可气的是该段代码的show_all参数死活传不过去,在rails s控制台中看到的总是/cn/store/index后面没有?show_all=true这段!当把button_to的method参数改为:post后,show_all参数可以正常传递到后台了,但我不想用post方式哦!
于是决定先用link_to试一下:

<%= link_to(t(".show_all_html"),store_index_path(show_all:true),class:‘locale‘)%>

生成的代码如下:

<a class="locale" href="/cn/store/index?show_all=true">显示所有商品</a>

注意链接url部分和button_to生成的是一模一样的!点击该链接后正确传递了参数.
难道必须用link_to而不能用button_to的:get方式传递参数吗?答案是否定的喽!一番搜索后,查到button_to使用如下方法实现:

<%= button_to(‘show all products‘,store_index_path,method: :get,params:{show_all:true})%>

rails中link_to与button_to的一个功能差异

标签:rails   link-to   button-to   

原文地址:http://blog.csdn.net/mydo/article/details/43610819

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!