rails form using multiple tables - ruby-on-rails

I am trying to create a form that updates a table. I want to have a dropdown button that pulls information from one table called "manufacturer" and once the form is submitted, stores the data in the "reviews" table.
This is my form:
<%= form_for(#review) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field" align= "center">
<h3>Select bat</h3>
<%= f.collection_select :bat_id, Manufacturer, include_blank: true %>
<h3>What do you like about this bat?</h3>
<%= f.text_area :pros, placeholder: "Enter what you like..." %>
<h3>What do you not like about this bat?</h3>
<%= f.text_area :cons, placeholder: "Enter what you don't like..." %></br>
</div>
<div align="center">
<%= f.submit "Add Review", class: "btn btn-large btn-info" %>
</div>
<% end %>
When you look at this line- <%= f.collection_select :bat_id, Manufacturer, include_blank: true %> I believe :bat_id tells the the form where to send the input from the user. (in this case to the :bat_id parameter in the review table)
How would I tell the form to select the dropdown options from the manufacturer table?
Update:
Would I need to add anything in the controller?

Look at the documentation http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_select
collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
# method: the field in your form's object
# collection: the collection of active records to display as options
# value_method: which method call in items of the collection to get the displayed value
# text_method: which method call in items of the collection to get the id value
So in your case:
<%= f.collection_select :bat_id, Manufacturer.all, :id, :name, include_blank: true %>
Given that Manufacturer model has a name field, otherwise you need to adapt

Related

Rails Form - Error when deselecting on a collection_select

I have a bare bones rails form. I have minimal javascript for adding and removing the category fields. I don't want it to be fancy so a rails specific solution is what I'm looking for.
The form is for Posts with a has_and_belongs_to_many relationship to Categories.
<%= form.collection_check_boxes :category_ids, Category.all, :id, :name, {prompt: "None", include_hidden: false}, {multiple: true} %>
<% #posts.categories.each do |category| %>
<%= form.fields_for :categories, category do |c_subform| %>
<div>
<%= f.hidden_field :_destroy %>
</div>
<div class="row clearfix">
<%= f.label :name, "Category name", class: 'form-label' %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<% if #posts.new_record? %>
<div>
<%= link_to "Remove Category", '#', class: "remove_fields", style: "color: red" %>
<%= link_to_add_fields "Add Category", form, :categories %>
</div>
<% end %>
<% end %>
<% end %>
I added the ability to select multiple categories and there is another fieldset below allowing the user to create new categories. The issue is while editing a post, if I deselect one of the previously selected categories (in this case, the one with ID of 3), on save I get the error: ActiveRecord::RecordNotFound Couldn't find Category with ID=3 for Post with ID=23.
I would love for the update action to just delete the posts_categories record connecting Post 23 and Category 3 without deleting Category 3.
I want to add that the form worked fine until I decided to add the multi-select functionality by making it checkboxes that could be deselected and also required the category names be unique.

Use Dropdown selection to call specific action in controller

I have a has_many through association for three models. One model has individual tests that can be administered. The second model is the name of a group of those tests. (The group name of triathlon will have associations to multiple records in the individual test model).
I want the user to be able to select a group name from a Dropdown
and when they do it passes a param to a specific action in a controller that then is tested through the association model.
I can get the form to look correctly, but not pass parameters to a specific action and then return to the same page.
I have searched and tried for hours to no avail. What’s the correct Cr form_for syntax (or something entirely different.)
Below is my current code
<% form_for #labwork, :url => {:action => "groupcreate"} do |f| %>
<%= f.form_group :lab_id, class: 'row' do |f| %>
<%= f.label "Group", class: 'control-label col-md-2' %>
<div class='col-12 col-md-10'>
<%= f.collection_select :lab_id, Labgroup.all, :id, :name, {prompt: "Choose a lab group "}, class: "form-control" %>
<%= f.error_messages %>
</div>
<% end %>
<div class="d-flex">
<div class="ml-auto">
<%= f.submit class: 'btn btn-primary' %>
<%= link_to "Cancel", labworks_path, class: 'btn btn-outline-default' %>
</div>
I also have a def creategroup in my labworks controller.

Checkboxes in single form for multiple objects

In trying to create a single form to add multiple objects, I followed this tutorial and got it working. Problem is, I can only enter values for string attributes and not for boolean attributes as it messes the params up. Where is my form going wrong?
http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/
<%= form_tag boa_constrictors_litter_hash_path do %>
<% #litter.each do |snake| %>
<%= fields_for 'offspring[]', snake do |f| %>
<%= f.hidden_field :type, :value => "BoaConstrictor" %>
<%= f.text_field :name, placeholder: "Name"%>
<%= f.label :gender %>
<%=f.select :gender, options_for_select([['Male', 'Male'],
['Female', 'Female']]) %>
<%= f.hidden_field :year, :value => "2017" %>
<%= f.label :available %>
<%= f.check_box :available %>
<%= f.label :private %>
<%= f.check_box :private %>
<%= f.label "Notes" %>
<%= f.text_field :notes %>
<% if #dame.hypo? or #sire.hypo? %>
<%= f.label "Hypo" %>
<%= f.check_box :hypo %>
<% end %>
<% if #dame.img? or #sire.img? %>
<%= f.label "IMG" %>
<%= f.check_box :img %>
<% end %>
<% end %><br>
<% end %>
<%= submit_tag %>
Ex; Creating two snakes, one named "first" w/ available: true and the other named "second" sends the following params which creates three snakes with incorrect attributes:
"offspring"=>[{"type"=>"BoaConstrictor", "name"=>"first", "gender"=>"Male",
"year"=>"2017", "available"=>"0"}, {"available"=>"1", "private"=>"0",
"notes"=>"", "hypo"=>"0", "img"=>"0", "type"=>"BoaConstrictor",
"name"=>"second", "gender"=>"Male", "year"=>"2017"}, {"available"=>"0",
"private"=>"0", "notes"=>"", "hypo"=>"0", "img"=>"0"}], "commit"=>"Save
changes"}
If I entered two animals, one named "first" with notes "works" and the other named "second " with notes "now", it gives the correct params and creates two animals correctly.
"offspring"=>[{"type"=>"BoaConstrictor", "name"=>"first", "gender"=>"Male",
"year"=>"2017", "available"=>"0", "private"=>"0", "notes"=>"works",
"hypo"=>"0"}, {"type"=>"BoaConstrictor", "name"=>"second", "gender"=>"Male",
"year"=>"2017", "available"=>"0", "private"=>"0", "notes"=>"now",
"hypo"=>"0"}], "commit"=>"Save changes"}
If I check any of the booleans in the form, the params chop at that attribute and repeat leading to extraneous objects and messing up the attributes of any of the objects that follow.
Solved
Check_box does not work correctly for attributes within an array as documented here: https://apidock.com/rails/ActionView/Helpers/FormHelper/check_box
Solution was to use check_box_tag
Instead of <%= f.check_box :private %>, using <%= check_box_tag 'offspring[][private]' %> works fine.
check_box does not work correctly for attributes within an array as documented here.
Solution was to use check_box_tag:
Instead of <%= f.check_box :private %>,
using <%= check_box_tag 'offspring[][private]' %> works fine.

Call edit action after selecting value in dropdown

The edit view page has the following dropdown:
<%= select_tag "Voiture", options_from_collection_for_select(#vehicles, :id, :model, params[:id].to_i) %>
When used, I would like to reload the page with the Vehicle chosen in the dropdown. I don't know whether to use :onchange => submit() or :action => 'edit'. Thanks.
Let's say we have a form like this(which is common for edit & new action)
and dynamically we are assigning ID to this form, hence for edit action this forms id will
Be 'edit_customer_form'
#_form.html.erb
<%= form_for(#customer, html: {id: params[:action] + '_' +'customer_form'}) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :vehicle_id %><br>
<%= f.select :vehicle_id,
options_from_collection_for_select(#vehicles, :id, :name) %>
</div>
<%= f.submit %>
<% end %>
Now, we want when the value in the selection box is altered the edit form(#edit_customer_form) should get submitted.
#application.js
$(document).ready(function(){
$('#edit_customer_form').on('change', '#customer_vehicle_id', function(){
$('#edit_customer_form').submit();
});
});
Here #edit_customer_form is the edit forms ID and #customer_vehicle_id is the ID of the selection box.
Check the complete code in below gist link:
https://gist.github.com/AjayROR/0a633ee493d78ff30332

Rails form fields empty after submitting form

This is my form:
<%= form_tag("/adverts", :method => "get") do %>
Order by:
<%= select_tag :order_by, options_for_select([['Ascending', 'ASC'], ['Descending', 'DESC']])%>
<%= text_field_tag :text%>
<%= submit_tag 'Change' %>
<% end %>
In my Adverts controller, index method, for now I am not doing anything and I can see that it is getting correct values from form,
=>but when page reloads after submission, fields values are empty but I want them to retain values.
So if I enter some text in text field, that text will still be there after submitting form .
Like this:
<%= select_tag :order_by, options_for_select([['Ascending', 'ASC'], ['Descending', 'DESC']], params[:order_by]) %>
and:
<%= text_field_tag :text, params[:text] %>
See the API for options_for_select and text_field_tag.
You need to create the form for an object if you want it to automatically get the objects values on reload.
<%= form_for #object do |form| %>
<%= form.text_field :name %> <!-- automatically gets re-populated with the value of #object on postback -->
<%= form.submit %>
<% end %>
If you really want to use form tags instead of a builder then you need to set the values manually after postback
<%= text_field_tag :text, some_string_value %>

Resources