Rails Form - Error when deselecting on a collection_select - ruby-on-rails

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.

Related

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.

create multiple nested resources with a single form

I'm creating user permissions for my project, so I created a model called "profile", each "profile" record will represent a module of my proyect, so a "user" has many "profiles", I need to create a form In which I can create multiple profiles to the user and modify all those records in a single form. The form would be like this , but I would like to know how I could do to create multiple nested records in a single form and that each one is independent since each record will have fields like the name of the module that identify it, for example "products"
So far I have something like this, but it only shows me a single field:
<div class="form-group">
<%= f.fields_for :profiles do |profile| %>
<%= perfil.hidden_field :Module, value: "Products" %>
<%= f.label :Bajas,"Bajas:", class: "control-label" %>
<%= f.check_box :Bajas %>
<%end%>
</div>
You should use form-group of div inside #user and change the div like this:
<%= form_for #user do |user| %>
<div class="form-group">
<%= f.fields_for :permission, #user.permission do |profile| %>
<%= perfil.hidden_field :Module, value: "Products" %>
<%= f.label :Bajas,"Bajas:", class: "control-label" %>
<%= f.check_box :Bajas %>
<%end%>
</div>
<% end %>

Rails: Dependent Fields inside a form

I want to implement dependent fields in my application. For that I'm using the dependent-fields-rails gem. I've set up everything with this tutorial. The good thing: It works. Kind of. In my brand model I have brands listet such as Adidas, Nike, ...
Now my two challenges:
I don't know what I have to fill in to the data-option-value=" " field because I want to show the select form for the category if a Brand is selected at all and not a specific one. If I put a value in the field (hardcoded) like data-option-value="Adidas" the category_select form only appears if I've chosen "Adidas" from the Brand dropdown.
I want to show only the matching categories for the Brand that was selected in step 1. My group model contains also the brand record so I can match a category to the brand.
To make it a bit more clear:
Brand model contains companies like Adidas, Nike, ...
Group model contains categories like Footwear, Shirts, ...
Here's what I got:
<div class="form-group">
<%= f.label :brand %>
<%= f.select(:brand, Brand.pluck(:company).uniq, {prompt:true}, {class: 'form-control'}) %>
</div>
<div class="form-group js-dependent-fields" data-select-id='warehouse_brand' data-option-value="Adidas">
<%= f.label :category %>
<%= f.collection_select(:category, Group.all, :brand, :name1, {prompt:true}, {class: 'form-control'}) %>
</div>
Any Ideas? Thanks a lot in advance!
I assume that a brand has many groups. If you don't want to use hard coded values then put the js-dependent-fields in a loop as shown in the code below.
<div class="form-group">
<%= f.label :brand %>
<%= f.select(:brand, Brand.pluck(:company).uniq, {prompt:true}, {class: 'form-control'}) %>
</div>
<% Brand.all.each do |b| %>
<div class="form-group js-dependent-fields" data-option-value= "#{b.company}" data-select-id="warehouse_brand">
<%= f.label :category %>
<%= f.collection_select(:category, Group.where(brand_id: "#{b.id}"), :brand, :name1, {prompt:true}, {class: 'form-control'}) %>
</div>
<% end %>
To show only the matching categories you can write a query that selects the related to the brand as shown in the code
Group.where(brand_id: "#{b.id}")
this actually works:
<div class="form-group">
<%= f.label :brand %>
<%= f.select(:brand, Brand.pluck(:company).uniq, {prompt:true}, {class: 'form-control'}) %>
</div>
<% Brand.all.each do |b| %>
<div class="form-group js-dependent-fields" data-option-value="<%= b.company %>" data-select-id="warehouse_brand">
<%= f.label :category %>
<%= f.collection_select(:category, Group.where(brand: b.company), :brand, :name1, {prompt:true}, {class: 'form-control'}) %>
</div>
<% end %>

Attempting to utilize a drop down menu in a form in ruby on rails

First off, I'm pretty new to Ruby and Ruby on rails, so bear with me.
I'm attempting to have my categories section of my form utilize my category table in my db so that when the author wants to select on a category, they can just select the drop down menu and choose one. For now, I've hard coded them and this works
<%= form_for(#article) do |f| %>
<% if #article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% #article.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.label :author_id %><br>
<%= f.text_field :author_id %>
</div>
<div class="field">
<%= f.label :category_id %><br>
<%= f.select (:title), [['Finance'], ['Marketing'], ['Programming'], ['Leisure'], ['Management'], ['Food']] %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
but, by switching the categories section to
<div class="field">
<%= f.label :category_id %><br>
<%= f.select :category_id, Category.all %>
</div>
it will give me a drop down box containing each hash, and I'm not to sure why, but I can't do Category.all.name to get the names (I'm assuming it is because it's in a hash). Any help would be great appreciated.
It looks like that you need to change you select use options_for_select tag:
<%= f.select :category_id, options_for_select(Category.all.collect {|c| [ c.name, c.id ] }), :include_blank => true %>
if you want to pre-populate category_id
<%= f.select :category_id, options_for_select(Category.all.collect {|c| [ c.name, c.id ]}, #article.category_id), :include_blank => true %>
For more information options_for_select
Have you defined the Category model in your Controller? The form can/will only know what the controller knows. It cannot know any more. If this form is attached to the articles_controller then it will have access to #article, but it won't have access to #category.
So this leaves you with a couple options. Define category somewhere in your controller, OR alternatively (and this would be my suggestion) setup some type of association for your Articles model.
Does Article have many Categories? This is a great opportunity to setup that has_many association, and then you can access the category model via Article's associations methods.
This is my suspicion, but we really don't have enough information here. Can you post your controller, and your article model so we can see everything that is going on? Also, what error do you get specifically?

Creating a Rails dropdown for related database

I have 2 models, venues and areas (areas consists of id and name fields). They are related as: one area has many venues and each venue belongs to an area.
To assign a venue to an area I am currently entering the area_id number into a text field in the create new venue page. I can then display which area the venue belongs to with:
<%= venue.area.name %>
Instead of having to enter the ID number of the area in the form I would like to have a dropdown listing the area names for all the area records and for the selected one to be associated with that venue on save.
The new venue form:
<% form_for #venue do |f| %>
<p>name: <br>
<%= f.text_field :name %></p>
<p>address line 1: <br>
<%= f.text_field :addressline1 %></p>
<p>address line 2: <br>
<%= f.text_field :addressline2 %></p>
<p>address line 3: <br>
<%= f.text_field :addressline3 %></p>
<p>area_id: <br>
<%= f.text_field :area_id %></p>
<%= submit_tag %>
<% end %>
I have tried:
<p>area_id: <br>
<%= collection_select(:area, :name, #areas, :id, :name) %>
But get:
You have a nil object when you didn't
expect it! You might have expected an
instance of Array. The error occurred
while evaluating nil.map
Any help is much appreciated!
It looks like #areas isn't defined and maybe a couple other issues as well. Try this:
<%= f.collection_select(:area_id, Area.all, :id, :name) %>
As aNoble said, it's right!
If you want to order by name, just use the following:
<%= f.collection_select :area_id, Area.order(:name),
:id, :name %>

Resources