【问题标题】:creating new pages in ruby on rails 6在 ruby​​ on rails 6 中创建新页面
【发布时间】:2020-05-29 10:08:30
【问题描述】:

我创建了一个带有脚手架的 rails 6 应用程序,它有两个字段 name_of_the_user 和 user_country,现在只有三个可能的国家“美国”、“澳大利亚”和“日本”我想将每个国家的用户移动到一个新的页。结果,我的 index.html.haml 应该有三个新链接,分别指向“USA”、“AUSTRALIA”和“JAPAN”,它们将我重定向到日本页面的用户、澳大利亚页面的用户和美国页面的用户。我是 ruby​​ 新手,找不到任何解决方案。

%h1 USER
= link_to 'New User', new_user_path
%table
 %thead
  %tr
  %th Name 
  %th Country

%tbody
- @users.each do |user|
  %tr
    %td= link_to user.name,user
    %td= user.country

【问题讨论】:

  • 你的索引apge和你的索引方法是什么样子的?

标签: ruby ruby-on-rails-5 ruby-on-rails-6


【解决方案1】:

您可以在同一索引页面上添加一些链接,但在视图中添加查询参数:

= link_to 'All Users', users_path
= link_to 'USA', users_path(country: 'USA')    
= link_to 'Australia', users_path(country: 'AUSTRALIA')
= link_to 'Japan', users_path(country: 'JAPAN')

当使用时,在控制器中为您的index 方法添加一个额外的数据库where 条件:

def index
  @users = User.all
  @users = @users.where(country: params[:country]) if params[:country].present?
end

只有当您的数据库中的国家/地区实际上仅以大写字符存储时,这才有效,就像您在问题中所写的那样。当它以小写或标题形式存储时,您需要更改查询字符串的格式或清理控制器中的输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 2016-06-20
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多