rails setting and reading a collection of parameters - ruby-on-rails

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

Related

rails: link_to to pass list of selected checkboxes into params

I am not sure what the correct approach is for my situation:
I want to create a link_to pushing all checkboxes with value="1" into an array, or individually if array is not possible, but I am at a loss of how to express that?
<% #cards.each do |card| %>
<%= check_box("#{card.name}", card.id, {checked: true}) %><%= "#{card.name}" %>
<% end %>
(Rails 4.2)
After a long time of dead ends, trying to make it a 'clean' solution I ended up with this very dirty approach. But as they say, done is better than perfect:
Create a link_to that would include all the cards, but add one additional params: user_selected_cards = "".
Create a javascript that listens to for checking/unchecking of the checkboxes and reads the id associated with that specific checkbox. Then take that incoming info and add or remove it to the actual url that the link_to generates by finding the user_seletected_cards= portion in the url and add or remove the id depending on if isn't or already is added to the list after the equal sign.

How to read values from multiple checkbox in ruby-on-rails

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

Rails custom form generator - radio button not in response parameters unless it has a value

Ok, I've been digging around and haven't found an answer to this. I have a pretty complex custom rails form generator application that renders pages, sections, & surveys (forms) from a database.
It does validation server side (haven't finished the javascript yet and want both types), and I have it working for all types of form input objects, except for radio buttons. Because I can't get it to submit radio buttons to show up in params when they are not checked. As opposed to just looking for radio buttons outside of the params, I'd like to find a way to check them in my response loop (if possible).
I've seen this suggestion of binding it to the model to make sure it validates, but my questions are unique and therefore I don't have a model object I'm binding it to.
My form is declared in one partial:
<%= form_tag take_surveys_path, :id => "take_surveys_new", :method => :post do %>
and my code for generating the radio button (part of a partial that looks at a question type field):
<% when 'Radio Button' %>
<% question.answers.each do |answer| %>
<%= radio_button "response[#{question.id}]content", question.question_text, answer.value %>
<%=answer.value%>
<br />
<% end %>
<% end %>
I iterate over params in my "take_survey_controller" and then check each question to see if it's valid, which includes regex and required validation based on some attributes set in my question object:
params[:response].each do |question_id, answer|
#find my questions and answers, call
if item.valid?
#do a bunch of saving and stuff...
end
end
but this never gets called for radio buttons because empty radio buttons don't post to the params.
Any suggestions or help? Happy to share more code if needed.
What you're looking for is a way to set a default value for your radio buttons. Checkboxes do this by default, but in this instance it doesn't look like it's happening for your radio buttons.
Try this:
<%= hidden_field "response[#{question.id}]content", question.question_text %>
<%= radio_button "response[#{question.id}]content", question.question_text, answer.value %>
It sounds like part of your validation should include checking input params. If a radio button isn't selected it won't submit a value, thus you need to have a list of question ids and ensure each question was submitted before moving into your params response loop.
array_of_question_ids.each do |id|
handle_missing_question(id) unless params[:response][id]
end
params[:response].each ...

Rails Dependent Form - Selecting a Specific Item from a Model

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 %>

Rails Form Builders - How to display a read only field or protect a field

I have created a form that needs to show data from 2 tables (parent and child). When the form is submitted only the child fields are updated (the parent fields are meant to be display only). While the parent model fields are displayed these need to be protected from updates (preferably via the formbuilder, rather than via css).
FWIW this is a pretty common master/detail use case. However I have not been able to find any examples of this - most of the examples I've seen seem to be trivial/single model display/update where all displayed fields are updateable).
Any ideas/samples/suggestion/tutorials/examples of real world, multi model Rails forms would be helpful.
TIA
Just out of interest, why bother going through the motions of creating a multi-model form when you only want to update the child record? My advice would be keep your form simple, I.e. make it a child form and just display the data from the parent record. If needs be, you could even style that display to look like part of the form, although I think that may throw the user off.
If you really need to do what you are doing, I would still use CSS to disable/readonly the input fields and in your controller update action, only pass the attributes you want to update into the update_attributes method call.
Finally, maybe look into the attr_protected method to prevent the fields you may want protecting from accidental mass-assignment.
I agree with tsdbrown, I don't think a complex form is required. If you'd like to learn more about complex forms or you really have your heart set on using a complex form I'd recommend watching the Railscasts episodes (73 - 75).
As tsdbrown said before, you are adding a complexity layer to your forms that's not need. If all you want is to update a detail model, while showing some info of it's parent, you could just do so with something like:
Order number: <%= #line_item.order.number %>
Order date: <%= #line_item.order.order_date %>
<% form_for #line_item do |f| %>
<%= f.label :quantity %>
<%= f.text_edit :quantity %>
<% end %>
When you'd like to edit both, then you can research on the field_for and nested forms methods (the Railscasts suggestion mentioned before it's great).
Thx for the responses which helped resolve my problem/question. Just want to close this out in case it helps others in the future.
Turns out I had been getting an error trying to reference my parent data element (patients.lname) as it was being passed in an array of results, rather than as a single result. In my view controller I had:
#visit = Visit.all(:select => "visits.id, visits.visittype, visits.visitdate, events.patient_id, patients.lname",
:conditions => ["visits.id = ?",params[:id] ],
:joins => "INNER JOIN events on events.id = visits.event_id INNER JOIN patients on patients.id = events.patient_id" )
In my view I had (this was giving me an invalid reference as I was doing a find all above):
<h1>Editing visit for patient :
<%= #visit.lname %> # should be <%= #visit[0].lname %>
</h1>
Below is the improved (and simpler) version where I find the specific record I need (basically replacing find all with find first):
#visit = Visit.find(:first, :select => "visits.id, visits.visittype, visits.visitdate, events.patient_id, patients.lname",
:conditions => ["visits.id = ?",params[:id] ],
:joins => "INNER JOIN events on events.id = visits.event_id INNER JOIN patients on patients.id = events.patient_id" )
And in the view:
<% form_for(#visit, :builder => LabelFormBuilder) do |f| %>
<%= f.error_messages %>
Name: <%= #visit.lname %>
<%= f.text_field :visittype %>
<%= f.date_select :visitdate %>
<p>
<%= f.submit 'Update' %>
</p>
<% end %>
Sometimes it's hard to see the wood for the trees! Hope this helps someone else.

Resources