How to read values from checkbox in rails.
Suppose I have brands and products.Under brands table, I have 3 brands say nike,reebok and puma. When none of the check box is selected It should display all the products say shirts,trousers,skirts. If nike brand is selected then should display onlt nike related products.Also user should have access to select more than 1 brands and we should able to display corresponding product details.
Conceptually what you are doing is a lot like creating a form that acts as a search engine (Ryan Bates does great screen casts and can help get you if you get lost http://railscasts.com/episodes/37-simple-search-form). Instead of entering text, the form uses checkboxes to create an array of brands the user wants to see.
First Create the form
<%= form_tag your_path_here_path, method: :get do %>
<%= label_tag :Nike %>
<%= check_box_tag 'brands[]', '1' #assuming 1 is the id of the Nike brand%>
<%= label_tag :Reebok %>
<%= check_box_tag 'brands[]', '2'%>
<%= label_tag :Puma %>
<%= check_box_tag 'brands[]', '3'%>
<%= submit_tag 'Get Products'%>
<%- end %>
Then in the controller processing this request search for the products that match brands in the form like this
Products.where('brand_id IN (?)', params[:brands])
To go a bit further. People use JS for these types of problems so that as the user checks different brands the products will automatically reload on the page without the user having to hit a submit button.
This could be accomplished by writing a JQuery function that listens to check events on your brands checkboxes and then
1) makes an Ajax call in the background to get all the relevant
products
2) Removes all the products you don't currently need on the page
3) Shows all the new products.
If you don't know any JQuery this project could be an interesting way to get started learning. Again, railscasts can help http://railscasts.com/episodes/136-jquery
Related
Hello I’m beginner on ruby on rails and I have to build an application for my studies.
It will have users who can select differents activities and then have a list of all the things that they need for these activities ( For example if they select « Fishing » they will have a list as « bundles, fishing rod … » ).
I have a bidirectional has_and_belongs_to_many relationship between activities and things.
I would like to display all the activities and if the user selects some activities it should show things related to those activities.
How can I build such a view?
I try to put an « if check_box true ? » but it doesn’t work …. If you can help me, I would be grateful !
To display my list of activities I'm using this :
<%= form_tag do %> <% #activities.each do |activity| %> <li> <%= check_box_tag 'activity_ids[]', activity.id %> <%= activity.name %> <%= activity.content %> </li> <% end %>
Since this is for an assignment I will just try to help you along but not give you the whole answer as your teacher wants you to learn it.
I would use the form_for as described in: https://apidock.com/rails/ActionView/Helpers/FormHelper/form_for
Then I would build the checkboxes using the collection_check_boxes method as shown here:
https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_check_boxes
It is unclear from your question but if the Things for each activity are already set, then you shouldn't need much more than this. If you try the methods above and have problems please edit your original question and I can try and help you further.
Try doing it via jQuery and ajax request. Create an action in a controller which retrieve data and call that action from the ajax request and then render the response data whereever you want.
I have a scenario where
a training Drill applies to a group of people playing sport at a
certain Grade (Elite, Adult, Junior),
and that Drill will develop them to Perform at a certain level (fundamental, advanced)
I am iterating through a Grades list and putting a dropdown list next to each Grade item so that the person creating the training drill can specify how that apply to developing them to perform at the level, as follows
<label>How will this drill improve performance?</label>
<% Grade.all.each do |g| %>
<% if g.activity_id == #drill.activity_id %>
<p>It will develop
<%= select(drill, :grade_ids, #performancelevels.map {|p| [p['development_title'], g.id.to_s + "-" + p.id.to_s] }) %>
performance for the <%= g.name %> level</p>
<% end %>
<% end %>
In my controller I am permitting
params.require(:drill).permit(... {:grade_ids => []} ...)
When the form submits I am only getting one value passed when I select several
Parameters: {... "grade_ids"=>"1-4"... "commit"=>"Create Drill"}
Any suggestions on the best way for me to collect up and send through these parameters?
Thanks for your help!!
Got this working. Attached javascript to onchange of the dropdown, added the values to a hidden field, then split the values out of the hidden field in the controller
I have a list of things users have created, and I am having trouble showing them based on who created them.
In my view I have
<%= form_tag({}, class: "form-inline") do %>
<%= label_tag("user_names", "Users") %>
<%= text_field_tag("user_names", params[:user_names]) %>
And then in my controller I am trying to scope it with this
if params[:user_names].present?
#random = #random.where(:user_id => :user_names)
I see the dropdown, but I'm trying to get is so the dropdown shows the users names and lets me select one, so that when I submit the form, I only see entries associated with that user.
What am I missing?
You need to find the users by username and join in the other model through the user association.
if params[:user_names].present?
#random = #random.joins(:user).where("users.username IN (?)", params[:usernames])
end
I have an object called a device that is associated with a customer. Once the customer orders a device, then the factory assigns the device to the customer, and the customer registers the device, and communication between the device and the rest of its associated functions can begin.
When I display the edit page to the factory administrator via the following:
<%= form_for #device do |f| %>
<%= render 'fields', f: f %>
The 'customer' field, which is itself defined in its own table, appears properly as a select dropdown. However, the default value for that select is not the currently assigned customer, but is just the current customer in the list. Is there a way using the above default rendering scheme to make the select dropdown use the current value for the device?
I've tried several variations on the theme:
<%= form_for #device do |f| %>
<%= render 'fields', f: f %>
<%= f.select :customer, options_for_select(#customers.each{|p| [p.name, p.id]}, #device.customer.name)%>
but these approaches just result in one gigantic dropdown that runs the entire width of the screen and, even then, does not show the appropriate default value. In addition, the f.select just shows the object ID of the customer, rather than the name itself.
From Rails api doc:
Given a container where the elements respond to first and last (such
as a two-element array), the “lasts” serve as option values and the
“firsts” as option text... If selected is specified, the matching
“last” or element will get the selected option-tag.
According to this:
<%= f.select :customer, options_for_select(#customers.map{|p| [p.name, p.id]}, #device.customer.id)%>
You have to set the selected option to the id (the "last" of your array [name, id]): #device.customer.id and use map.
Hope this helps!
I'm new to Rails so be gentle. I've got a model, 'Event', with the the following information: 'sport', 'home_team', 'away_team', and 'time' in datetime.
Now I want to enable the user to 'follow' a specific event and am trying to find the best way to do so. Ideally, I'd like a form with dependent drop down lists. For example, the user first picks a 'day', then a 'sport', then selects from a relevant list of 'events' of that 'day' and 'sport'. This association is then stored in a rich join table called 'following'.
I've seen tutorials on complex forms that involve multiple models, but what about when everything is from the same model? How do build a form to grab a handful of relevant records. I only have a few distinct values for 'sport', so I wasn't sure it made sense to give it its own model. And can I easily get events on a certain date from a 'datetime' value?
There a lot of ways to go about this, here is one option:
Since you want to see multiple events, you'd probably start off focused on the index action. Start off by creating and index action, but add some hooks to filter it, i.e.
def index
if params[:sport]
#events = Event.where("sport = ?",params[:sport])
else
#events = Event.all()
end
end
Now, if you've defined your routes like this:
resources :events
You'll have a a route /events that will accept a get request and route you to the index action.
But if you want a form where you can select things, a form will by default POST, but you could create a form that GETs to '/events'
i.e. in app/views/events/index.html.erb
<%= form_tag '/events', :method=>:get %>
Then, you want to create your form elements that will send the params.
i.e.
<%= select_tag 'sport', '<option>baseball</option><option>football</option>' %>
Put in a submit button
<%= submit_tag 'See Events'
Then 'end' your form with
<% end %>
Now when you click on the 'See Events' button, you will send a get request to the route '/events', and the 'sport' parameter will show up in the index action, filtering the events.
To keep things simple and all in the index view, after your form you'd list all the events.
<% #events.each do |e| %>
Sport: <%= e.sport %><br/>
Home Team: <%= e.home_team %><br/>
Away Team: <%= e.away_team %><br/>
Time: <%= e.time.strftime('%H %M') %><br/>
<% end %>