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.
Related
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.
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 have 2 conotrollers and 3 models:
Models:
problem.rb
class Problem < ActiveRecord::Base
has_many :problemtags
has_many :tags, :through => :problemtags
end
tag.rb
class Tag < ActiveRecord::Base
validate :name, :presence => true
has_many :problemtags
has_many :problems, :through => :problemtags
end
problemtag.rb
class Problemtag < ActiveRecord::Base
belongs_to :problem
belongs_to :tag
end
problems_controller.rb
class ProblemsController < ApplicationController
def new
#all_tags = Tag.all
#new_problem = #problem.problemtags.build
end
def create
params[:tags][:id].each do |tag|
if !tag.empty?
#problem.problemtags.build(:tag_id => tag)
end
end
end
def problem_params
params.require(:problem).permit(:reporter_id, :status, :date_time, :trace_code)
end
tags_controller.rb
//tags_controller is generate with scaffold
And I have below code in problems view:
new.html.erb
<%= fields_for(#new_problem) do |f| %>
<div class="field">
<%= f.label "All Tags" %><br>
<%= collection_select(:tags, :id, #all_tags, :id, {}, {:multiple => true}) %>
</div>
<% end %>
when I run the project, the problem's view is show, but when I complete the textfields and select tags and then click on submit button, I get below error:
NoMethodError in ProblemsController#create
undefined method `[]' for nil:NilClass
Extracted source (around line #22):
#problem = #reporter.problems.build(problem_params)
params[:tags][:id].each do |tag|
if !tag.empty?
#problem.problemtags.build(:tag_id => tag)
end
I do not understand the problem. any one can describe the problem to me?
As stated by your answers, your issue is that you're not sending the right data to your controller (and consequently params[:tags] will be blank):
Form
You're firstly missing the form_builder object in your collection_select (so your tags will likely not be sent inside the correct params hash). Although this may be by design, you need to ensure you're passing the data properly:
<%= fields_for(#new_problem) do |f| %>
<div class="field">
<%= f.label "All Tags" %><br>
<%= f.collection_select(:tags, :id, #all_tags, :id, {}, {:multiple => true}) %>
</div>
<% end %>
Params
Secondly, we cannot see your form or params hash. This is vital, as your form needs to look like this:
<%= form_for #variable do |f| %>
<%= f.text_field :value_1 %>
<%= f.text_field :value_2 %>
<% end %>
This creates a params hash like this:
params { "variable" => { "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" }}}
This will be the core reason why your controller will return the [] for nil:NilClass error - you'll be referencing params which don't exist. You'll need to call params[:variable][:tags] as an example
If you post back your params hash, it will be a big help
You could try using validate :tag_id, :presence => true to check for presence of the needed params.
I found 2 problems in my code:
in new.index.html(in problem view), the submit button is in the form_for and I write the field_for outside the form_for and when I click on submit button, the params hash of tags didn't create.
In collection_select, I forgot to add the name parameter of tag.
Correct new.html.erb code:
<%= form_for #problem do |f| %>
status: <%= f.text_field :status %><br/>
datetime: <%= f.datetime_select :date_time %><br/>
trace code: <%= f.text_field :trace_code %><br/>
<%= fields_for(#new_problem) do |f| %>
<div class="field">
<%= f.label "All Tags" %><br>
<%= collection_select(:tags, :id, #all_tags, :id,:name, {}, {:multiple => true}) %>
</div>
<% end %>
<%= f.submit %>
<% end %>
Thanks for all of the answers.
Is There Any way we can submit into two tables in single rails form_for/simple_form_for which both the tables are associated to each other?
Example:-
<%= form_for #ob do |f| %>
<%= f.text_field :name %>
<%= f.text_field :another_col --> this is another table column(having association)
<%f.button :submit %>
<%end%>
The trick is to add accepts_nested_attributes_for to your parent model, and do as below
MODEL
class Ob < ActiveRecord::Base
has_many :foo
accepts_nested_attributes_for :foo, allow_destroy: true
end
ERB
<%= form_for #ob do |f| %>
<%= f.text_field :name %>
<% f.foo do |fo| %>
<%= fo.text_field :another_col %> <%=# this is another table column(having association)%>
<% end %>
<%f.button :submit %>
<%end%>
CONTROLLER
#your params would look like below
params = { ob: {
name: 'joe', foos_attributes: [
{ another_col: 'Bar' }
]
}}
Ob.create(params[:ob])
I have a model Person with the following attributes:
:name, :state, :age, :town
Let's say I want to be able to edit all of the attributes except for :name from that Person's edit view. Is there a "rails" way to do this, and if so what would I write without looping through each attribute and creating a form?
Right now, I've got something like this:
<%= form_for #person do |person_form| %>
<%= person_form.fields_for :age do |age_form| %>
<%= age_form.text_field :age %>
<% end %>
<% end %>
And I would do that for each attribute.
It would be just a standard form since the object you're wrapping the form around has all of the attributes.
<%= form_for #person do |f| %>
<%= f.text_field :state %>
<%= f.text_field :age %>
<%= f.text_field :town %>
<%= f.submit %>
<% end %>
Of course, you can add labels and whatever else you need to the form.