I'm trying to use a collection_select to assign a branch_id to a visit (in a form where a user books a visit with a branch) but I'm getting the error "wrong number of arguments (7 for 4..6)".
I've been using the documentation here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select And as far as I can see, my code matches the example.
Here is my collection_select:
<div class="field">
<%= f.label :branch_id, "Please Pick Service Provider/Branch you would like to visit:" %><br>
<%= f.collection_select(:visit, :branch_id, Branch.all, :id, :branch_name_select, {prompt: "Select the Branch/Service"}, {:required => true}) %>
</div>
branch.rb:
class Branch < ActiveRecord::Base
belongs_to :user
has_many :visits
def branch_name_select
"#{branch_name}, #{address_line_1}, #{address_line_2}, #{city}, #{postcode}"
end
end
visit.rb:
class Visit < ActiveRecord::Base
belongs_to :branch
belongs_to :user #:as => 'created_by'
validates_uniqueness_of :time_from, :scope => [:date_from, :location], :message=>"slot is already taken on selected date"
end
This line
<%= f.collection_select(:visit, :branch_id, Branch.all, :id, :branch_name_select, {prompt: "Select the Branch/Service"}, {:required => true}) %>
should be
<%= f.collection_select(:branch_id, Branch.all, :id, :branch_name_select, {prompt: "Select the Branch/Service"}, {:required => true}) %>
Related
I have two models in a has_one belongs_to relationship:
class Facility < ApplicationRecord
has_one :machine
end
class Machine < ApplicationRecord
belongs_to :facility
end
In the _form partial for saving machines, I have a collection_select that picks the facility:
<%= form.collection_select :facility, Facility.all, :id, :facility_name,
{prompt: "Select a faclity"}, {class: "form-control"} %>
In the MachinesController I have facility_id permitted as shown below:
def machine_params
params.require(:facsummary).permit(:facility_id, ....)
end
I think I have done everything right, but despite selecting a facility in the dropdown,I get the error:
"Facility must exist"
Where could I be going wrong?
Try to the following to add facility_id instead of facility
<%= form.collection_select :facility_id, Facility.all, :id, :facility_name, {prompt: "Select a faclity"}, {class: "form-control"} %>
and the strong parameter method it would machine like below
params.require(:machine).permit(:facility_id, ....)
Or try if above not work
<%= form.collection_select(:facility_id, Facility.all, :id, :facility_name, {prompt: 'Select a faclity'}, {:class => 'form-control'}) %>
It's tested
I am trying to create a web application to practise my Ruby on Rails skill. I have a few entities in my database manufacturers, models, tints, prices
manufacturers {id, name} - stores the make of the car
models {id, manufacturer_id, name} - stores the models of the car
tints {id, manufacturer_id, model_id, front, sides, rear} - stores the length of tint required
prices {id, description, price } - stores the price of the item
I created a page to generate a quotation for window tinting. The page includes drop-down menus to let user to select manufacturer, model, type of film(front), type of film(side+rear)
Below is the code for the form
<%= form_tag('/quotation/tints/generate') do %>
<%= label :manufacturer_id, 'Manufacturer' %>
<div class="field">
<%= collection_select(:tint, :manufacturer_id, Manufacturer.order(:name), :id, :name, {:prompt => "Select Manufacturer"}) %>
</div>
Model:
<div class="field">
<%= grouped_collection_select(:tint, :model_id, Manufacturer.order(:name), :models, :name, :id, :name, {:prompt => "Select Model"}) %>
</div>
<%= label :price_front, 'Front Tint' %>
<div class="field">
<%= collection_select(:price, :price_front, Price.order(:name), :id, :name, {:prompt => "Select Front Tint"}) %>
</div>
<%= label :price_rear, 'Size and Back Tint' %>
<div class="field">
<%= collection_select(:price, :price_rear, Price.order(:name), :id, :name, {:prompt => "Select Side & Rear Tint"}) %>
</div>
<div class="form-group">
<%= submit_tag 'Submit' %>
</div>
<% end %>
When the form is submitted, it should be redirected to /quotation/tints/generate and display the value from the dropdown menu. However, I received an error, saying that Couldn't find Manufacturer with 'id'=. The code that caused the error is shown below
def generate
#manufacturers = Manufacturer.find(params[:manufacturer_id])
end
Here is the parameter from the debug log
{"utf8"=>"✓",
"authenticity_token"=>"Pl2bXiRT0AoF4i0h1RCHDbuvaKJNZOkV5ULQHKxDQgZzBWWLJ2mH7ddb9akwgxbloxBIHoVaT3pcwoIGcRufpg==",
"tint"=>{"manufacturer_id"=>"7", "model_id"=>"6"},
"price"=>{"price_front"=>"1", "price_rear"=>"2"},
"commit"=>"Submit"}
I can see that the id of each drop down value are shown up correctly in the parameter list. However, I coundn't able to print the value at /quotation/tints/generate nor get the name of the manufacturer or model.
Here is routes.rb:
get '/quotation/tints' => 'tints#quotation', :as => 'tints_quotation'
post '/quotation/tints/generate' => 'tints#generate', :as => 'generate_tints_quotation'
Tint.rb:
class Tint < ApplicationRecord
has_many :manufacturers
has_many :models
belongs_to :manufacturer
belongs_to :model
validates_uniqueness_of :model_id, :scope => [:manufacturer_id]
end
Model.rb:
class Model < ApplicationRecord
belongs_to :manufacturer, :dependent => :destroy
validates :name, :presence => true
validates_uniqueness_of :name, :scope => [:manufacturer_id]
before_save :capitalize_content
end
Manufacruter.rb:
class Manufacturer < ApplicationRecord
has_many :models, :dependent => :destroy
validates :name, :presence => true, uniqueness: { case_sensitive: false }
before_save :capitalize_content
end
tints.controller.rb:
def quotation
render 'quotation'
end
def generate
#manufacturers = Manufacturer.find(params[:manufacturer_id])
end
generate.html.erb:
<%= #manufacturers.name %>
I'm trying to print the manufacturer selected
I have tried multiple ways to define it, but I am still facing the same error. Any help is greatly appreciated.
In your params, manufacturer_id is a nested value of tint, as opposed to being a direct key of the params hash. Try the following:
def generate
#manufacturers = Manufacturer.find(params[:tint][:manufacturer_id])
end
I looked for two days on the web but I am still blocked to update a child object of a parent object.
My parent:
class Pass < ActiveRecord::Base
has_many :fields
attr_accessor :fields_attributes
accepts_nested_attributes_for :fields, :allow_destroy => true, :update_only => true
My child:
class Field < ActiveRecord::Base
belongs_to :pass
My form view:
<%= f.fields_for :fields do |field|%>
<div class="control-group">
<%= field.label :id, :class => 'control-label' %>
<%= field.label :value, :class => 'control-label' %>
<div class="controls">
<%= field.text_field :value, :class => 'text_field' %>
</div>
</div>
<% end %>
I also define permitted parameters thanks to:
def pass_params params.require(:pass).permit(:pass,
:description,
:organization_name,
:logo_upload,
:icon_upload,
:strip_upload,
fields_attributes: [:id,:value])
#params.require(:pass).permit!
end
I have no problem to create a pass with 5 fields in my passes_controller
def new
#pass = Pass.new
5.times {#pass.fields.build}
##fields = #pass.fields
end
My problem happens is that child fields of my pass are not updated after an edit of the pass. I always get initial values (at the creation of the pass) of fields.
I tried to update using different ways without success
if #pass.update_attributes(pass_params)
if #pass.update_attributes[params[:pass][:fields_attributes]]
if #pass.update_attributes(params[:fields_attributes])
When I update my pass, the pass_params looks like this:
{"description"=>"Test22gg", "organization_name"=>"Toto", "fields_attributes"=>{"0"=>{"id"=>"30", "value"=>"testf"}, "1"=>{"id"=>"29", "value"=>"test"}, "2"=>{"id"=>"28", "value"=>"test"}, "3"=>{"id"=>"27", "value"=>"test"}, "4"=>{"id"=>"26", "value"=>"test"}}}
I don't see which requirement or thing I forget to update these fields!
I have seen multiple questions similar to this, but none worked for me.
I have a team model:
class Team < ActiveRecord::Base
has_one :p1, :class_name => "Player", :foreign_key => 'player_id', :validate => true
has_one :p2, :class_name => "Player", :foreign_key => 'player_id', :validate => true
end
in my team's _form.html.erb, I am referring to players as
<%= f.collection_select :p1, Player.all, :id, :name %>
However, on form submission, I see the error:
Player(#28401456) expected, got String(#14111904)
Application Trace | Framework Trace | Full Trace
app/controllers/teams_controller.rb:47:in `new'
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"GSIcEvROFnvgGWT4HvE2VNqRw4NxU1J8iAw/WhZeRLk=",
"team"=>{"p1"=>"1"},
"commit"=>"Create Team"}
And here is the code at line
def create
#team = Team.new(params[:team])
.....
end
Any ideas please?
Finally, this worked:
<%= f.collection_select :p1_id, Player.all, :id, :name %>
Here is the magic:
My migration has t.references p1 and that created a column of p1_id in the database.
When The form is submitted, rails is looking to fill in the id of the reference at:
def create
#team = Team.new(params[:team])
.....
end
I could be wrong, but my guess is that instead of
<%= f.collection_select :p1, Player.all, :id, :name %>
you need
<%= f.collection_select :p1, :team_id, Player.all, :id, :name %>
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
Try this:
<%= f.collection_select :player_id, Player.all, :id, :name %>
I am trying to build a simple_nested_form in my Ruby on Rails app. When I submit my form I am getting some unknown error because it is just redirecting back to the form to input again. Here is the output in the rails server console for when I submit the form. It looks like there is some random "0" => thrown in there.
Parameters: {"machine"=>{"name"=>"2134", "ip_adress"=>"2", "machine_employees_attributes"=>{"0"=>{"machine_id"=>"1", "employee_id"=>"2"}}}, "commit"=>"Create Machine"}
I have a machine model which has_many :machine_employees
and a machineemployee model which belongs_to :machine
Do you have any idea why this 0 => could be appearing because I think it is what is giving me the issues.
Here is the code for my models.
Machine
class Machine < ActiveRecord::Base
# Relationships
has_many :machine_employees
has_many :employees, :through => :machine_employees
accepts_nested_attributes_for :machine_employees, :reject_if => lambda{ |me| me[:employee_id].blank? }
attr_accessible :ip_adress, :name, :machine_employees_attributes
# Validations
validates_presence_of :name, :ip_adress
end
MachineEmployee
class MachineEmployee < ActiveRecord::Base
before_validation :set_default
# Relationships
belongs_to :machine
belongs_to :employee
attr_accessible :employee_id, :machine_id, :end_date, :start_date
# Validations
validates_presence_of :employee_id, :machine_id, :start_date
private
# Callback Methods
def set_default
self.start_date = Date.today
self.end_date = nil
end
end
New Machine Form
<div class="row-fluid">
<div class="span3">
<h1>Add a Machine</h1>
<br />
<%= simple_nested_form_for #machine do |f| %>
<%= render "machine_fields", :f => f %>
<%= f.button :submit %>
<%= link_to 'Back', machines_path %>
</div>
<div class="span4">
<h4>Assign an Employee to This Machine</h4>
<%= f.simple_fields_for :machine_employees do |me_form| %>
<!-- render nested machine_employee fields-->
<%= render "machine_employee_fields", :f => me_form %>
<% end %>
</div>
<% end %>
</div>
Machine Employee Fields Partial
<%= f.input :machine_id, :as => :hidden, :input_html => { :value => #machine.id } %>
<%= f.input :employee_id, collection: #employees, :id => :name, :prompt => "Select ..." %>
The 0 is thrown in there because the machine model has_many machine_employees. When you use nested forms, it passes a pseudo-array for has_many relations. So, if you tried to submit 2 machine employees, your hash would look like this:
Parameters: {"machine"=>{"name"=>"2134", "ip_adress"=>"2", "machine_employees_attributes"=>{
"0"=>{"machine_id"=>"1", "employee_id"=>"2"},
"1"=>{"machine_id"=>"1", "employee_id"=>"3"}
}
}, "commit"=>"Create Machine"}
This way you can access the machine_employees passed from the form by doing params[:machine][:machine_employees_attributes][0] or params[:machine][:machine_employees_attributes][1]. Note that if this was a has_one relationship, then the machine_employees_attributes key would be changed to machine_employee_attributes and there would be no numerical index.
I suspect the problem is that your machine model must accept_nested_attributes_for :machine_employees and must also have attr_accessible :machine_employees_attributes.