Rails——传递额外的参数通过一个链接 - Rails - passing extra parameters through a link

- 此内容更新于:2016-02-01
主题:

我有两个表在我的应用程序。用户表和用户有很多活动的活动——确切地说是总计(3)。我有一个主页上面有三个按钮。如果用户按下按钮,我要导航到活动索引页和设置属性activity_type=1。如果用户按下按钮2,我要导航到活动索引页和设置activity_type=2等等。现在我:在我的活动/index.html。erb文件我想有三个条件:它似乎并不承认我activity_type参数中包含的链接。我怎么做呢?

原文:

I have two tables in my application. The user table and the activities - the user has many activities (3 in total to be exact).

I have a home page with 3 buttons on it. If the user presses button one, I want to navigate to the activities index page and set the attribute activity_type to = 1. If the user presses button 2, I want to navigate to the activities index page and set the activity_type to = 2 etc. Right now I have:

<%= link_to 'Personal Activity', user_activities_path(:user_id => current_user.id, :activity_type => 1) %>
<%= link_to 'Physical Activity', user_activities_path(:user_id => current_user.id, :activity_type => 2) %>
<%= link_to 'Community Activity', user_activities_path(:user_id => current_user.id, :activity_type => 3) %>

In my activities/index.html.erb file I want to have three conditions:

If the activity_type = 1 for current_user
  Do X
Elsif the activity_type = 2 for current_user
  Do Y
Else
  Do X
End

It doesn't seem to be recognising the activity_type parameter I have included in the link. How do I do this?

网友:你怎么试着抓取?像什么?

(原文:How did you tried fetching activity_type? like params[:activity_type]?)

楼主:现在我有这个索引视图:<%=如果current_user.activities。activity_type==>1%。我不知道我在哪里我会从或者获取activity_type使用params[:activity_type]吗?

(原文:Right now I have this in my index view: <%= if current_user.activities.activity_type == 1 %> . I'm not sure where I would fetch the activity_type from or where I use params[:activity_type]?)

网友:那些是链接导航到索引页吗?如果是应该工作

(原文:Are those links navigating to index page? If so params[:activity_type] should work)

解决方案:
如果这些链接真的带你到页面,然后你可以访问。我也建议你把逻辑。
原文:

If those links really taking you to the index page, then you can access activity_type with params[:activity_type]. Also I recommend you to put the logic in the controller#action.

def index
  @activity_type = params[:activity_type]

  case @activity_type
  when 1
    #your logic
  when 2
    #your logic
  when 3
    #your logic
  else
    #some code
  end
end
解决方案:
这些参数附加到这样的参数,你可以访问它们,或者仅仅是这样的:
原文:

These parameters are appended to params and you can access them like these:

activity_type = params[:activity_type]

or simply like this:

if params[:activity_type] == 1
  Do something
else
  Do something
end