将参数传递给控制器​​

时间:2015-11-17 01:06:45

标签: ruby-on-rails hyperlink

所以我有用户标记最喜欢的帖子。我试图调整索引以仅显示最喜欢的帖子。

我的索引控制器看起来像这样

def index
  require 'soundcloud'
  @streamid = '?client_id=7e24fb69b20b922b683870511ae8d2d1'
  @client = Soundcloud.new(:client_id => '7e24fb69b20b922b683870511ae8d2d1')
  if params[:search]
    @posts = Post.search(params[:search]).order("created_at DESC")
  elsif params[:genre]
    @posts = Post.tagged_with(params[:genre]).order("created_at DESC")
  elsif params[:favorites]
    @posts = Post.first
  else
    @posts = Post.reorder('votes desc').find_with_reputation(:votes, :all).first(10)
  end
end

我的link_to按钮看起来像这样

<li><%= link_to ("<i class='glyphicon glyphicon-heart'></i> My Favorites").html_safe, root_path(:param => :favorites) %></li>

网址更改为

  

http://localhost:3000/?param=favorites

但该页面没有更新到控制器中的@posts变量。

我需要做什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

只需要两个步骤:

  1. 在视图中更改参数:

    <li><%= link_to ("<i class='glyphicon glyphicon-heart'></i> My Favorites").html_safe, root_path(:favorites => 1) %></li>

    它会生成指向http://localhost:3000/?favorites=1

  2. 的链接
  3. 在您的控制器中,检查参数&#39;收藏夹&#39;作为一个字符串。替换

    elsif params[:favorites]

    elsif params[:favorites].present? and params[:favorites].to_s == '1'