I do not understand how to setup forms with related resources in Rails 4.
My models:
class Task < ActiveRecord::Base
belongs_to :category
accepts_nested_attributes_for :category
end
class Category < ActiveRecord::Base
end
I'm trying to setup a form where I can simply select the "category" from a drop down box.
How do I setup my controller and form view to accomplish this?
Try this:
<%= form_for #task do |f| %>
<%= f.collection_select :category_id, Category.all, :id, :name, {}, { :multiple => false } %>
<% end %>
This assumes you have an attribute in your Category model called name.
Add category_id to your strong parameters in your Tasks Controller.
An example with and without simple_form
<%= simple_form_for #object do |f| %>
<%= f.input :name %>
<%= f.association :company %>
<%= f.button :submit %>
<% end %>
And without sf
<%= form_for #object do |f| %>
<%= f.collection_select :company_id, Company.all, :id, :name =>
<% end %>
Both will produce a dropdown of company's using the name in the select list.
Related
I'm trying to come up with a contact form that creates a contact record and potentially multiple location records, if multiple locations are checked in a list of checkboxes. I thought of having all location records created and then destroyed, if they aren't checked. I don't think that's optimal though.
I'm using many to many relationships in the models.
This is what they look like at the moment:
contact.rb
class Contact < ApplicationRecord
has_many :contact_locations, dependent: :destroy
has_many :locations, through: :contact_locations
accepts_nested_attributes_for :contact_locations, allow_destroy: true, reject_if: :empty_location?
private
def empty_location?(att)
att['location_id'].blank?
end
end
location.rb
class Location < ApplicationRecord
has_many :locations, dependent: :destroy
has_many :contacts, :through => :contact_locations
has_many :contact_locations
end
contact_location.rb
class ContactLocation < ApplicationRecord
belongs_to :location
belongs_to :contact
end
contacts_controller.rb
def new
#contact = Contact.new
#locations = Location.all
4.times {#contact.contact_locations.new}
end
private
def contact_params
params.require(:contact).permit(:name, :phone, ..., contact_locations_attributes: [:location_ids])
end
new.html.rb
<%= form_with model: #contact do |f| %>
...
<%= #locations.each do |location| %>
<%= f.fields_for :contact_locations do |l| %>
<%= l.check_box :location_id, {}, location.id, nil %><%= l.label location.name %>
<% end %>
<% end %>
...
<% end %>
Does anyone how to make it work properly?
I'm working on Ruby 2.5.1 and Rails 5.2.1.
Thanks a lot.
I think your solution is the form objects pattern.
You can have something like this:
<%= form_for #user do |f| %>
<%= f.email_field :email %>
<%= f.fields_for #user.build_location do |g| %>
<%= g.text_field :country %>
<% end %>
<% end%>
And convert it in something more readable that permits you to instance the locations inside the registration object, checking the value of the checkboxes.
<%= form_for #registration do |f| %>
<%= f.label :email %>
<%= f.email_field :email %>
<%= f.input :password %>
<%= f.text_field :password %>
<%= f.input :country %>
<%= f.text_field :country %>
<%= f.input :city %>
<%= f.text_field :city %>
<%= f.button :submit, 'Create account' %>
<% end %>
Here you will find how to apply the pattern: https://revs.runtime-revolution.com/saving-multiple-models-with-form-objects-and-transactions-2c26f37f7b9a
I ended up making it work with Kirti's suggestion on the following question:
Rails Nested attributes with check_box loop
It turns out I needed to make a small adjustment in my form's fields_for tag.
Thanks a lot the help!
I am trying to create a dropdown select on a form. I have a HABTM association between professors and classrooms:
Classroom Model:
class Classroom < ApplicationRecord
has_and_belongs_to_many :professors
end
Professor Model:
class Professor < ApplicationRecord
has_and_belongs_to_many :classrooms
end
Strong Params:
def classroom_params
params.require(:classroom).permit(:name, :professor_ids => [])
end
I am trying to find a way to use f.select instead of select_tag inside the form. But when I do it, the database does not save the values. This way works:
<%= form_for #classroom do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<% array = Professor.all.map { |professor| [professor.user.name, professor.id] } %>
<%= select_tag "classroom[professor_ids][]", options_for_select(array) %>
<% end %>
But I am trying like that and it is not working:
<%= form_for #classroom do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<% array = Professor.all.map { |professor| [professor.user.name, professor.id] } %>
<%= f.select :professor_ids, options_for_select(array) %>
<% end %>
The view works correctly but when I submit the form, the value doesn't go to to the classroom_params. I tried to debug it stopping the controller after the submit and I got this:
The params came correctly with all the information submitted, but the classroom_params came missing the professor_ids.
Is there a way to do this dropdown using f.select?
You whitelisted the array of 'professor_ids', but your 'select' input returns 1 string ("prefessor_ids" => "2" from you screenshot). Maybe you want to set the select as 'multiple'? (I have not tested it, but i think params will be whitelisted correctly after that)
<%= form_for #classroom do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<%= s.collection_select :professor_ids, Professor.all, :id, :name, multiple: true %>
<% end %>
where
class Professor
...
delegate :name, to: :user
end
Update
You probably don't have 'cfg' variable in your controller action.
I am trying to drop in enum values setup with the 'Enumerize' gem into the radio collection select field on a rails-bootstrap-form.
An example is shown how to do this with an ActiveRecord collection. How should I modify the example
<%= f.collection_radio_buttons :skill_level, Skill.all, :id, :name %>
So that it can accept an enum that is setup on my model
<%= f.collection_radio_buttons :level %>
skill.rb
class Skill < ActiveRecord::Base
extend Enumerize
enumerize :level, in: [:good, :ok, :bad ]
end
The Enumerize documentation says
SimpleForm
If you are using SimpleForm gem you don't need to specify input type
(:select by default) and collection:
<%= simple_form_for #user do |f| %>
<%= f.input :sex %>
<% end %>
and if you want it as radio buttons:
<%= simple_form_for #user do |f| %>
<%= f.input :sex, :as => :radio_buttons %>
<% end %>
If you're using simple-form, then the documentation says all you need to do is this:
<%= simple_form_for #skill do |f| %>
<%= f.input :level %>
<% end %>
If you're using rails-bootstrap-form, the documentation shows how to use collection_radio_buttons with Rails's built-in enum functionality, which you aren't using. So I believe you would need to pass in the Skill.level.options call as the collection values, but the :level method for (as the method, value_method, and text_method arguments):
<%= bootstrap_form_for #skill do |f| %>
<%= f.collection_radio_buttons :level, Skill.level.options, :level, :level %>
<% end %>
I have a model Vendors which has many Products. I would like to add many Products at a time without showing the existing products that belong to the vendor.product relationship. I only want to display the form for new objects. Currently everything is working but on the add page I am getting all of the objects that are tied to the instance relationship which is #vendor.products. If I do not use that relationship in the form I do not get any fields.
Here is my new Product action:
'def new
#vendor = Vendor.find(params[:vendor_id])
5.times {#vendor.products.build}
end'
Here is my form:
<%= form_for #vendor do |f| %>
<%= f.fields_for :products do |g| %>
<p>
<%= g.label :name %>
<%= g.text_field :name %>
<%= g.label :category %>
<%= g.select :category, options_for_select(['Parts', 'Labor', 'Extras', 'Shop']) %><br>
</p>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
The Product Model:
class Product < ActiveRecord::Base
belongs_to :vendors
attr_accessible :name, :category, :vendor_id, :vendor_sku, :products
validates :name, :uniqueness => true
validates :category, :presence => true
validates :name, :presence =>true
end
Just to reiterate, I would only like to show the blank, newly built objects as opposed to all of the products tied to that #vendor 's relationship. I must be overlooking a form structure to get this done but I just have not been able to figure it out. Thanks for looking.
Only render the nested fields if the product in a new record.
<%= form_for #vendor do |f| %>
<%= f.fields_for :products do |g| %>
<% if g.object.new_record? %>
<p>
<%= g.label :name %>
<%= g.text_field :name %>
<%= g.label :category %>
<%= g.select :category, options_for_select(['Parts', 'Labor', 'Extras', 'Shop']) %><br>
</p>
<% end %>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
I'm a bit stuck on a 'has_one' and 'belongs_to' relationship and getting it to properly display in Formtastic. I have a person model that has one picture (a profile picture). I want the user to be able to select the picture using radio buttons. So far, I have:
<% form.inputs do %>
<%= form.input :picture, :as => :radio, :collection => #pictures %>
<% end %>
However, this fails (because the foreign key is stored on the 'belongs_to' side of associations in Rails. Any suggestions?
Ended up using custom controller code to fix. Use a variety of filters, etc.
Came across this in the "related" sidebar. I think this is a good use case for nested attributes -- from the Formtastic README:
Nested forms are also supported (don’t forget your models need to be setup correctly
with accepts_nested_attributes_for). You can do it in the Rails way:
<%= semantic_form_for #post do |form| %>
<%= form.inputs :title, :body, :created_at %>
<%= form.semantic_fields_for :author do |author| %>
<%= author.inputs :first_name, :last_name, :name => "Author" %>
<% end %>
<%= form.buttons %>
<% end %>
Or the Formtastic way with the :for option:
<%= semantic_form_for #post do |form| %>
<%= form.inputs :title, :body, :created_at %>
<%= form.inputs :first_name, :last_name, :for => :author, :name => "Author" %>
<%= form.buttons %>
<% end %>