Reputation: 4940
I'm sorting through the User model on the User Index page. Right now, all I have is two options that can be accessed through radio buttons. I may be doing this the wrong way, it works for now, but if you have a better way then please shed some light. The main question I have is why are the radio buttons not checked when they are selected?
User's Index Controller
if params[:sort] == "popular"
@users = User.most_popular_users
elsif params[:sort] == "recent"
@users = User.most_recent_users
end
User.rb
scope :most_popular_users, -> do
results = select {|user| user.followers }
results.sort! {|t1, t2| t2.followers.count <=> t1.followers.count}
end
scope :most_recent_users, -> do
results = User.all
results.sort! {|t1, t2| t2.created_at <=> t1.created_at}
end
Again, I'm not sure how correct that is in terms of "best practices", so if it's wrong I would love to change it as well. Back to the question...
My view looks like this:
<%= form_tag find_users_path, :method => 'get' do %>
<%= radio_button_tag(:sort, "popular") %>
<%= label_tag(:sort_popular, "Popular") %>
<%= radio_button_tag(:sort, "recent") %>
<%= label_tag(:sort_recent, "Recent") %>
<%= submit_tag "Submit" %>
<% end %>
Right now, when you submit the form, it sorts the Users properly, but the selected radio is not selected on the respective page. So when you submit the form the find the popular
users, the url looks like:
/people?sort=popular
but the radio button for popular
is not checked.
Upvotes: 2
Views: 1969
Reputation: 2784
You need to do something like the following:
radio_button_tag(:sort,"popular", params[:sort].eql?("popular"))
The 3rd argument for the radio_button_tag
helper accepts a true or false value to know if the radio is checked or not. More info here:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-radio_button_tag
Upvotes: 3