Refactoring Ruby on Rails link_to with sorting

NoobException

I'm very new to Rails, Databases, and web development in general, right now my feature is working but I'm 100% sure it's not the cleanest or most Ruby-esq way of doing it. Basically I want to use two separate links that sort the same table by different columns, without using two controller actions and two views. I'd rather just user the one index action that takes a parameter indicating how to sort the returned data.

Current Controller:

Controller

def index
  @casinos = Casino.order('name ASC')
end

def casinos_by_region
  @casinos = Casino.order('location ASC')
end

And links in the view

 %h3 Sort by:
 = link_to 'Name', casinos_path
 %br
 = link_to 'Location', casinos_by_region_path

I read the docs but I didn't see an obvious way on passing an argument from the view to controller using a link_to path? I know I could do it other ways, but I refuse to believe I can't do it this way. Sorry for the dumb question!

CDub

How about this:

def index
  @casinos = Casino.order("#{params[:sort_param]} ASC")
end


%h3 Sort by:
= link_to 'Name', casinos_path(:sort_param => "name")
%br
= link_to 'Location', casinos_path(:sort_param => "location")

The path in link_to can take a hash which are parameters on the request. You can set a parameter (in this case sort_param) with what value you want to sort by, then use that in your order on the index method of the controller.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Ruby on Rails:link_to javascript

来自分类Dev

Ruby on Rails中的Link_to

来自分类Dev

<%= link_to%>中的Ruby on Rails <%=%>

来自分类Dev

通过排序重构Ruby on Rails link_to

来自分类Dev

Ruby on Rails:link_to 与 button_to

来自分类Dev

Ruby on Rails link_to对n00b的解释?

来自分类Dev

ruby on rails在link_to中包装代码块

来自分类Dev

Ruby On Rails在link_to中使用帮助器方法

来自分类Dev

Ruby on Rails将确认添加到link_to

来自分类Dev

ruby rails删除link_to之后的空间而没有HAML

来自分类Dev

Ruby on Rails-具有url参数的Link_to对象

来自分类Dev

无法从link_to访问模型中声明的Ruby on Rails方法

来自分类Dev

Ruby on Rails - 使用 if 条件在 link_to 中传递参数?

来自分类Dev

Rails动态link_to的

来自分类Dev

Rails:link_to参数

来自分类Dev

Rails link_to问题

来自分类Dev

Ruby on Rails:如何使用link_to添加“ aria-hidden ='true'”

来自分类Dev

如何在Ruby on Rails的link_to中为href提供图像

来自分类Dev

Ruby on Rails link_to使用variable_name_path和控制器:variable_name

来自分类Dev

在rails 4中通过ruby中的link_to方法传递参数

来自分类Dev

为什么在Ruby on Rails中不使用!important就不能更改link_to文本颜色?

来自分类Dev

Ruby On Rails:如何在select_tag中添加link_to

来自分类Dev

Ruby-on-Rails 添加 current_page?到我的 link_to

来自分类Dev

在 Ruby on Rails 中将 option_for_select 值作为参数传递给 link_to

来自分类Dev

Rails dataTables添加link_to

来自分类Dev

Rails,HAML,使用link_to

来自分类Dev

环绕HTML与Rails link_to

来自分类Dev

Rails HightCharts添加link_to

来自分类Dev

Rails的link_to如何工作?