Rails form_for check_box - ruby-on-rails

I'm trying to create a basic survey app. On my take survey page I'm looping through and displaying each answer option as a radio button or checkbox as a form_for to create a user's choice. The choices are working great for the questions that are single choice (or radio buttons), but they aren't saving for multi select questions. I'm pretty sure this has to do with the form I have for the checkbox.
It seems like I should do
<%= f.check_box :answer_id, answer.id %> <%= answer.title %> <br>
similar to how I'm creating the radio button but that throws an error
undefined method `merge' for 14:Fixnum
Here's my code that displays:
<h3>Questions:</h3>
<ul><% #survey.questions.each do |question| %>
<li><p><%= question.title %></p></li>
<% choice = question.choices.build %>
<% if question.single_response == true %>
<%= form_for [question, choice] do |f| %>
<% question.answers.each do |answer| %>
<%= f.radio_button :answer_id, answer.id %> <%= answer.title %><br>
<% end %>
<%= f.hidden_field :survey_id, value: #survey.id %>
<%= f.submit %>
<% end %>
<br />
<% else %>
<%= form_for [question, choice] do |f| %>
<% question.answers.each do |answer| %>
<%= f.check_box :answer_id %> <%= answer.title %> <br>
<%= f.hidden_field :survey_id, value: #survey.id %>
<% end %>
<%= f.submit %>
<% end %>
<br />
<% end %>
<% end %>
</ul>
Any idea what I need to do to get it to save the answer_id to the choice so that it actually creates the choice?
Thanks!

This question is a few years old but I think it deserves a better answer. Since you are using form_for (a model backed form), then you probably want to use the form_for check_box method that you originally tried to use. In your case, it would look like this:
<%= f.check_box :choice, { :multiple => true }, answer.id, false %>
Here is the doc on this.

For checkboxes, you actually want to return an array as the parameter. There is a little funny syntax to this because we don't actually want to use the form builder methods. It should look something like this (adapt to your specific model names and methods)
<%= check_box_tag 'choice[answer_ids][]', answer.id %>
Using this syntax should tell Rails to compile all of the checked checkbox values into an array.
This Railscast goes over the topic.

Related

ActiveAdmin nested form duplicate

I know there are multiple questions with a similar title to this, but I haven't found anything that resembled my problem. If there is already a solution and thus my question is a duplicate, I'm sorry - I just didn't find it, it's not that I didn't search.
I'm using ActiveAdmin with the ActiveSkin theme. I have a form for my model Agent where I want to use the nested forms for a has_many relation. I created this code in a partial:
<%= semantic_form_for [#agent], builder: ActiveAdmin::FormBuilder do |f| %>
<%= f.semantic_errors %>
<%= f.inputs 'General Information' do %>
<%= f.input :name %>
<%= f.input :description %>
<% end %>
<%= f.inputs 'Capture Columns' do %>
<%= f.has_many :capture_columns, new_record: 'Add Column' do |column| %>
<%= column.input :column_name %>
<%= column.input :column_datatype %>
<% end %>
<% end %>
<%= f.actions do %>
<%= f.action :submit %>
<li class="cancel"><%= link_to 'Cancel', :back %></li>
<% end %>
<% end %>
Basically, this is working, but it looks like this:
Why is the html duplicated (I checked it, it's exactly the same)? What am I doing wrong?
EDIT:
The inner HTML for the nested form is duplicated, too:
Not saying it's the right behavior, but according to the docs, you need to avoid printing to the template when using has_many.
Try using <%- or <% instead of <%= in the f.has_many declaration and block.
There is a loop hear. The problem is simple to solve, just get in the loop and understand why it is looping and how to fix it. You should use binding.pry to test it. You can set a breakpoint in the form with <% binding.pry %> or you can print variables like <% puts column %> in your server log.
<%= f.has_many :capture_columns, new_record: 'Add Column' do |column| %>
<%= column.input :column_name %>
<%= column.input :column_datatype %>
<% end %>

Couldn't save collection_radio_buttons in array Ruby on Rails

We have a problem to save the values of the radio_buttons of a loop. It doesn't save in an array.
The SavedAnswer model has an has_and_belongs_to_many relation with the MultipleChoiceAnswer model.
This is my code:
<%= form_for #saved_answer do |f| %>
<% #questions.each do |question| %>
<%= collection_radio_buttons(:saved_answer, :multiple_choice_answer_ids , question.multiple_choice_answers, :id, :title) do |c| %>
<%= c.radio_button %>
<%= c.label %>
<% end %>
<% end %>
<%= f.submit "Submit" %>
<% end %>
My output is
Parameters: {"utf8"=>"✓", "authenticity_token"=>"57I9yLZMccvcb3Bn5/pw7kES0c9CUAGs33yCXoS0Urm1Yek/Baz8Hl7fO8Yl/OVZWLKsX7qrwOlqEBoXrGkcxQ==", "saved_answer"=>{ "multiple_choice_answer_ids"=>"1"}, "commit"=>"Submit"}
Thanks in advance!
You have form_for with |f| and collection with |f|.
It's not a good decision, i think. That can cause problems.
If not - write what you receive in params when trying to save.
Just use check boxes for your issue:
<%= form_for #saved_answer do |f| %>
<% #questions.each do |question| %>
<%= check_box_tag "saved_answer[multiple_choice_answer_ids][]", question.id, #saved_answer.multiple_choice_answer_ids.include?(question.id) %>
<%= question.title %>
<% end %>
<%= f.submit "Submit" %>
<% end %>
Refer: http://railscasts.com/episodes/17-habtm-checkboxes?view=asciicast

Concatenate multiple fields on submit into a single array/field

I have two models: QuestionnaireResult and QuestionnaireOption.
The options are dynamic.
QuestionnaireResult has two columns: date_submitted and results. I want the results column to be some sort of array of the QuestionnaireOption and their value...
i.e.
option_id / value
1 / 50
2 / false
3 / true
I submit data using this form, however it's not complete and not working because I don't know what name to give the text_fields (undefined method 'not_sure_what_to_name_this' for #<Admin::QuestionnaireResult:0x4a5ef9>):
<%= form_for(#questionnaire_result) do |f| %>
<% if #questionnaire_result.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#questionnaire_result.errors.count, "error") %> prohibited this questionnaire_result from being saved:</h2>
<ul>
<% #questionnaire_result.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% #questionnaire_options.each do |questionnaire_option| %>
<% if questionnaire_option.field_type == 'Textbox' %>
<div class="field">
<%= f.label questionnaire_option.option %><br />
<%= f.text_field :not_sure_what_to_name_this %>
</div>
<% elsif questionnaire_option.field_type == 'Checkbox' %>
<div class="field">
<%= f.label questionnaire_option.option %><br />
<%= f.check_box :not_sure_what_to_name_this %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
What name do I give text_field and how do I go about saving the results and storing them in a column as an array? Or is there better ways of going about this?
Check out this reference, where it says:
2.2 Binding a Form to an Object
While this is an increase in comfort it is far from perfect. If Person
has many attributes to edit then we would be repeating the name of the
edited object many times. What we want to do is somehow bind a form to
a model object, which is exactly what form_for does.
It goes on to show examples and elaborate on the discussion. So, the fields you use in the form_for are that model's fields. To show an example, in:
<%= form_for Feed.new, id: "feed_add" do |f| %>
<%= f.submit "Add Feed", class: 'formlabel' %>
<%= f.text_field :feed_url, class: 'forminput', :autocomplete => :off %>
<% end %>
the model is Feed and the text_field is :feed_url, so this updates Feed.feed_url. It is returned to the controller in params[:feed]['feed_url'].
If you can show your model, I can advise further.
To follow up on the other part of your question, "how do I go about saving the results and storing them in a column as an array? Or is there better ways of going about this?", that's a bit different.
If what you want to do is build an array, you might want to use form_tag instead of form_for. form_for is specifically for models. form_tag is a more generalized interface for objects not necessarily models. You can see that in the same reference. To show an example:
<%= form_tag feeds_path, method: 'get', id: "feed_search" do %>
<%= submit_tag " Search ", feed_url: nil, class: 'formlabel' %>
<%= text_field_tag :search, params[:search], class: 'forminput', :autocomplete => :off %>
<% end %>
Here, the value of :search is returned in params[:search].
Regarding how to do it, you should return this information to your controller where it can process it. Views are for display. The controller can easily build and process the array so that it can be used in its decisions and/or routing.

Using a Form_for with an each loop

I'm trying to create a form in Rails that allows a user to select certain photos from a larger list using checkboxes. Unfortunately, I haven't found any similar examples and most posts out there are unhelpful. Any ideas on how to solve this?
<div>
<%= form_for :photos, url: trip_path, method: "PUT" do |f| %>
<% #photos.each_with_index do |image, index|%>
<img src="<%= image.url %>" ><br>
<span> <%=image.caption%> | <%=image.lat %> | <%= image.long %>
<%= f.hidden_field "url", :value => image.url %>
<%=check_box_tag('photo') %>
</span>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
</div>
API docs states that a form_for
creates a form and a scope around a specific model object
so, you cannot use it with a collection.
A possible way to do it, is to use the form_tag instead of form_for and check_box_tag (which you already have).
The behavior you've depicted is categorically impossible using form_form. However, if you're willing to forgo form_for (and there's no reason why you shouldn't, given your criteria), you can imitate the behavior depicted by nesting a foreach loop – each loop containing a form_for block – within a form_tag:
<div>
<%= form_tag trip_path, method: "PUT" do |f| %>
<% #photos.each do |photo|%>
<img src="<%= photo.url %>" ><br>
<span> <%= photo.caption%> | <%= photo.lat %> | <%= photo.long %>
<%= fields_for "photos[#{photo.id}]", photo do |p| %>
<%= p.hidden_field 'url', :value => photo.url %>
<%= p.check_box 'photo'
<% end %>
</span>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
</div>

Rails Nested Attributes Doesn't Insert ID Correctly

I'm attempting to edit a model's nested attributes, much as outline here, replicated here:
<%= form_for #person do |person_form| %>
<%= person_form.text_field :name %>
<% for address in #person.addresses %>
<%= person_form.fields_for address, :index => address do |address_form|%>
<%= address_form.text_field :city %>
<% end %>
<% end %>
<% end %>
In my code, I have the following:
<%= form_for(#meal) do |f| %>
<!-- some other stuff that's irrelevant... -->
<% for subitem in #meal.meal_line_items %>
<!-- # Edit 2: I need to display information here about the subitem
Which I can't find a way to pass it to the partial, or work in
this manner for existing items
-->
<%= subitem.food.name %>
<%= subitem.food.calories %>
<%= f.fields_for subitem, :index => subitem do |line_item_form| %>
<%= line_item_form.label :servings %><br/>
<%= line_item_form.text_field :servings %><br/>
<%= line_item_form.label :food_id %><br/>
<%= line_item_form.text_field :food_id %><br/>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
This works great, except, when I look at the HTML, it's creating the inputs that look like the following, failing to input the correct id and instead placing the memory representation(?) of the model. As a result, an update fails:
<input type="text" value="2" size="30" name="meal[meal_line_item][#<MealLineItem:0x00000005c5d618>][servings]" id="meal_meal_line_item_#<MealLineItem:0x00000005c5d618>_servings">
EDIT:
The reason I'm attempting to do it in this method is that I need to gather some information on associations for existing meal_line_items. For example, in the area where I took out code, I have some code to the effect of:
<%= subitem.food.name %>
<%= subitem.food.calories %>
Getting this information won't work if I am using a form builder with partials, at least, not in my trials.
Edit 2:*
See the edit in the code. Here's my MealLineItem
class MealLineItem < ActiveRecord::Base
# Associations ---------------------
belongs_to :food
belongs_to :meal
end
And meal accepts_nested_attributes for the model. As you can see it belongs to both food and meal model. For the existing meal_line_item I need to do something like:
meal_line_item.food.name
Is there f. missing from <%= fields_for?
--edit
Have you tried:
<%= f.fields_for 'meal[meal_line_item][]', subitem do |line_item_form| %>
--edit
Docs say that it should work without loop too:
<%= form_for(#meal) do |f| %>
<!-- some other stuff that's irrelevant... -->
<%= f.fields_for :meal_line_items do |line_item_form| %>
<%= line_item_form.label :servings %><br/>
<%= line_item_form.text_field :servings %><br/>
<%= line_item_form.label :food_id %><br/>
<%= line_item_form.text_field :food_id %><br/>
<% end %>
<%= f.submit %>
<% end %>
Have to test this but maybe this approach?
_form
<%= form.fields_for :meal_line_items do |meal_line_item_form| %>
<% #meal.meal_line_items.each do |meal_line_item| %>
<%= render :partial => "meal_line_items/meal_line_item", :locals => { :meal_line_item_form => meal_line_item_form, :meal_line_item => meal_line_item } %>
<% end %>
<% end %>
meal_line_items/_meal_line_item.erb
<%= meal_line_item_form.label :servings %><br/>
<%= meal_line_item_form.text_field :servings %><br/>
<%= meal_line_item_form.label :food_id %><br/>
<%= meal_line_item_form.text_field :food_id %><br/>
EDIT
here's a link to an example for setting the formbuilder iterator directly (Rails 2.3.8 though). The associations between Outbreak -> Incidents -> Location should be similiar to the ones for Meal -> Meal_line_items -> Food.
AJAX update of accepts_nested_attributes_for partials
After searching high and low, I found the error. Although I was modifying the partial and was receiving a NameError it's because I was calling the partial from a helper method - exactly the same problem as stated in the following question:
rails fields_for render partial with multiple locals producing undefined variable

Resources