code_m
code_m

Reputation: 35

creating new pages in ruby on rails 6

I have created a rails 6 app with scaffold that has two fields, name_of_the_user and user_country, now there are only three possible countries "USA", "AUSTRALIA" & "JAPAN" I want to move users from each country to a new page. As a result my index.html.haml should have three new links for "USA", "AUSTRALIA" & "JAPAN" which redirect me to users of japan page, users of Australia page and users of USA page. I am new to ruby and not able to find any solution for this.

%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

Upvotes: 0

Views: 125

Answers (1)

spickermann
spickermann

Reputation: 106802

You could just add some links to the same index page but with query parameters to your view:

= 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')

And when use add an additional database where conditions to your index method in the controller:

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

This will only work when the country in your database is actually stored only in uppercase characters like you wrote in your question. When it is stored downcase or titleized then you would need to change the format of the query string or sanitize the input in your controller.

Upvotes: 2

Related Questions