Updating two tables with one to many relationship via form - ruby-on-rails

I am trying to update my two tables through my form but I am getting this error:
Started POST "/test" for ::1 at 2014-12-02 00:15:21 -0800
Processing by UsersController#create as JS
Parameters: {"utf8"=>"✓", "users"=>{"first_name"=>"sdfdsfdsf", "last_name"=>"dsfdsfds", "email"=>"3213213#hotmail.com", "phone_number"=>"23123213", "message"=>"sdfdsfsdfdsfkjsdfksdfk;adklsfjksadfksjdfklsdf"}, "commit"=>"Save Users"}
Completed 500 Internal Server Error in 1ms
ArgumentError (wrong number of arguments (1 for 0)):
app/controllers/users_controller.rb:32:in `create'
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_source.erb (2.6ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_trace.text.erb (0.4ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_request_and_response.text.erb (0.6ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/diagnostics.text.erb (12.2ms)
I have been reading examples and documentation and I think I wrote my form correctly but I think my controller is missing some aspects because I am new to rails.
Here is my schema:
ActiveRecord::Schema.define(version: 20141130075753) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "contact_requests", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "message", null: false
t.integer "user_id"
end
add_index "contact_requests", ["user_id"], name: "index_contact_requests_on_user_id", using: :btree
create_table "users", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name", null: false
t.string "last_name", null: false
t.string "email", null: false
t.string "phone_number"
end
end
Models:
class User < ActiveRecord::Base
has_many :contact_requests
validates(:first_name, presence: true)
validates(:last_name, presence: true)
validates(:email, presence: true)
accepts_nested_attributes_for :contact_requests
end
class ContactRequest < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :message, presence: true, length: { maximum: 500 }
end
user controller:
def create
if !(User.find_by(email: params[:users][:email]))
#user = User.new(user_params)
#contact_request = ContactRequest.new(contact_request_params)
#contact_request.save
#user.save
else
#contact_request = ContactRequest.new(contact_request_params)
#contact_request.save
end
end
private
def user_params
# strong_parameters, which requires us to tell Rails exactly which parameters
# we want to accept in our controllers
params.require(:users).permit(:first_name, :last_name, :email, :phone_number)
end
end
form:
<!-- contact -->
<section id="contact">
<div class="container">
<div class="title-container">Contact Us</div>
<div class="title-caption">Reach us at (415)-911-9999</div>
<%= form_for(:users, remote: true, id: "contact-form", class: "contact-input") do |f| %>
<div class="col-md-12">
<div class="col-md-6">
<div class="contact-input-margin form-group">
<%= f.text_field(:first_name, class: "form-control", placeholder: "First name")%>
</div>
<div class="contact-input-margin form-group">
<%= f.text_field(:last_name, class: "form-control", placeholder: "Last name") %>
</div>
<div class="contact-input-margin form-group">
<%= f.email_field(:email, class: "form-control", placeholder: "Email") %>
</div>
<div class="contact-input-margin form-group">
<%= f.telephone_field(:phone_number, class: "form-control", placeholder: "Phone number") %>
</div>
</div>
<div class="contact-input-margin col-md-6">
<div class="form-group">
<%= f.fields_for :contact_requests do |builder| %>
<%= f.text_area(:message, class: "form-control contact-margin", rows: "8", placeholder: "Message...") %>
<% end %>
</div>
</div>
</div>
<%= f.submit(class: "btn btn-xl") %>
<% end %>
</div>
</section>

Related

Rails accepts_nested_attributes_for not working with has_many relationship and cocoon gem

I'm using the cocoon gem to build a form that creates a Tournament. A Tournament has_many Games. Cocoon lets me dynamically add more games to the form.
When I call #tournament.save, it generates the following errors:
Games team one must exist
Games team two must exist
tournament.rb
class Tournament < ApplicationRecord
has_many :games
accepts_nested_attributes_for :games, allow_destroy: true
end
game.rb
class Game < ApplicationRecord
belongs_to :tournament, optional: false
belongs_to :team_one, polymorphic: true
belongs_to :team_two, polymorphic: true
belongs_to :field, optional: true
end
schema.rb
ActiveRecord::Schema.define(version: 2019_12_24_011346) do
...
create_table "club_teams", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "fields", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "games", force: :cascade do |t|
t.bigint "tournament_id", null: false
t.string "team_one_type", null: false
t.bigint "team_one_id", null: false
t.string "team_two_type", null: false
t.bigint "team_two_id", null: false
t.bigint "field_id", null: false
t.date "date"
t.datetime "start_time"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["field_id"], name: "index_games_on_field_id"
t.index ["team_one_type", "team_one_id"], name: "index_games_on_team_one_type_and_team_one_id"
t.index ["team_two_type", "team_two_id"], name: "index_games_on_team_two_type_and_team_two_id"
t.index ["tournament_id"], name: "index_games_on_tournament_id"
end
create_table "high_school_teams", force: :cascade do |t|
t.string "school_name"
t.string "team_name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "tournaments", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
add_foreign_key "games", "fields"
add_foreign_key "games", "tournaments"
end
tournaments_controller.rb
class TournamentsController < ApplicationController
...
def create
#tournament = Tournament.new(tournament_params)
if #tournament.save
redirect_to #tournament
else
render 'new'
end
end
private
def tournament_params
params
.require(:tournament)
.permit(:name, games_attributes: [:id, :_destroy, :team_one_id, :team_two_id, :field_id, :date, :start_time])
end
end
request parameters in tournaments_controller#create
{
"authenticity_token"=>"iB4JefT9jRdiOFKok38OtjzMwd6Dv3hlHP/QZRtlFgMuVZfbn9PFD7Lebc1DuvfL6/IatDpS5CiubTci5MsCFg==",
"tournament"=>{
"name"=>"foo",
"games_attributes"=>{
"1577935885397"=>{
"team_one_id"=>"high-school-team-2",
"team_two_id"=>"club-team-2",
"date"=>"",
"start_time"=>"",
"_destroy"=>"false"
}
}
},
"commit"=>"Create Tournament"
}
tournament_params in tournaments_controller#create
<ActionController::Parameters {
"name"=>"foo",
"games_attributes"=><ActionController::Parameters {
"1577937916236"=><ActionController::Parameters {
"_destroy"=>"false",
"team_one_id"=>"high-school-team-2",
"team_two_id"=>"club-team-2",
"date"=>"",
"start_time"=>""
} permitted: true>
} permitted: true>
} permitted: true>
It seems to me that the tournament_params match what the accepts_nested_attributes documentation is expecting under One-to-many, so I don't see why there is an error.
Nested attributes for an associated collection can also be passed in
the form of a hash of hashes instead of an array of hashes:
Member.create(
name: 'joe',
posts_attributes: {
first: { title: 'Foo' },
second: { title: 'Bar' }
}
)
has the same effect as
Member.create(
name: 'joe',
posts_attributes: [
{ title: 'Foo' },
{ title: 'Bar' }
]
)
Edit:
tournaments/new.html.erb
<h1>Create a tournament</h1>
<%= render 'form' %>
<%= link_to 'Back', tournaments_path %>
tournaments/_form.html.erb
<%= form_with model: #tournament, class: 'tournament-form' do |f| %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %>
</p>
<section class="games">
<%= f.fields_for :games do |game| %>
<%= render 'game_fields', f: game %>
<% end %>
<hr>
<p>
<%= link_to_add_association "Add game", f, :games,
data: {
association_insertion_node: '.games',
association_insertion_method: :prepend
}
%>
</p>
</section>
<p>
<%= f.submit %>
</p>
<% end %>
tournaments/_game_fields.html.erb
<section class="nested-fields">
<hr>
<p><strong>Game</strong></p>
<%= render "games/form_fields", f: f %>
<p><%= link_to_remove_association "Remove game", f %></p>
</section>
games/_form_fields.html.erb
<section>
<% if HighSchoolTeam.all.count + ClubTeam.all.count < 2 %>
<p>You neeed at least two teams to create a game. Create more high school and/or club teams first.</p>
<% else %>
<section class="game-form">
<p>
<%= f.label :team_one %><br>
<%= f.select :team_one_id, nil, {}, class: "team-one-dropdown" do %>
<optgroup label="High School Teams">
<% HighSchoolTeam.all.each do |high_school_team| %>
<option value="high-school-team-<%= high_school_team.id %>"><%= high_school_team.school_name %></option>
<% end %>
</optgroup>
<optgroup label="Club Teams">
<% ClubTeam.all.each do |club_team| %>
<option value="club-team-<%= club_team.id %>"><%= club_team.name %></option>
<% end %>
</optgroup>
<% end %>
</p>
<p>
<%= f.label :team_two %><br>
<%= f.select :team_two_id, nil, {}, class: "team-two-dropdown" do %>
<optgroup label="High School Teams">
<% HighSchoolTeam.all.each do |high_school_team| %>
<option value="high-school-team-<%= high_school_team.id %>"><%= high_school_team.school_name %></option>
<% end %>
</optgroup>
<optgroup label="Club Teams">
<% ClubTeam.all.each do |club_team| %>
<option value="club-team-<%= club_team.id %>"><%= club_team.name %></option>
<% end %>
</optgroup>
<% end %>
</p>
<p>
<%= f.label :field %><br>
<%= f.collection_select(:field_id, Field.all, :id, :name) %>
</p>
<p>
<%= f.label :date %><br>
<%= f.date_field :date %>
</p>
<p>
<%= f.label :start_time %><br>
<%= f.time_field :start_time %>
</p>
</section>
<% end %>
</section>
You seem to have problem saving team and not an issue of Cocoon gem.
Since you customize your select value to club-team-id and high-school-team-id. I think you just need to change it to something like this:
<option value="HighSchoolTeam-<%= high_school_team.id %>"><%= high_school_team.school_name %></option>
and
<option value="ClubTeam-<%= club_team.id %>"><%= club_team.name %></option>
Then the params will be
{
"authenticity_token"=>"iB4JefT9jRdiOFKok38OtjzMwd6Dv3hlHP/QZRtlFgMuVZfbn9PFD7Lebc1DuvfL6/IatDpS5CiubTci5MsCFg==",
"tournament"=>{
"name"=>"foo",
"games_attributes"=>{
"1577935885397"=>{
"team_one_id"=>"HighSchoolTeam-2",
"team_two_id"=>"ClubTeam-2",
"date"=>"",
"start_time"=>"",
"_destroy"=>"false"
}
}
},
"commit"=>"Create Tournament"
}
then you need to modified your params by:
# Adding before_action on top of your controller
before_action :modify_params, only: [:create, :update]
private
# Not the cleanest way, but this is what I can think of right now.
def modify_params
params.dig(:tournament, :games_attributes).each do |game_id, game_attribute|
team_one_type = game_attribute[:team_one_id].split('-').first
team_one_id = game_attribute[:team_one_id].split('-').last
team_two_type = game_attribute[:team_two_id].split('-').first
team_two_id = game_attribute[:team_two_id].split('-').last
params[:tournament][:games_attributes][game_id] = game_attribute.merge(
team_one_type: team_one_type,
team_one_id: team_one_id,
team_two_type: team_two_type,
team_two_id: team_two_id
)
end
end
# And update this method to allow team_one_type and team_two_type
def tournament_params
params.require(:tournament)
.permit(:name, games_attributes: [:id, :_destroy, :team_one_id, :team_two_id, :team_one_type, :team_two_type, :field_id, :date, :start_time])
end

Custom field for f.select - Allowing user to type

I want a user (candidate) to select his skills (like python, rails, node..) while he is signing up.
I know I can use the following:
new.html.erb
<%= f.select(:skill, [['Python', 'Python'],
['Java', 'Java'],
['Rails', 'Rails'],
],
{ :multiple => true, :size => 5 }
) %>
BUT
What if I want the user to add a custom field?
Imagine the user has also the skill Javascript. As it is now, he cannot selected it.
How can I allow him to add a custom field in the f.select?
schema.rb
create_table "candidates", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "skill"
t.index ["email"], name: "index_candidates_on_email", unique: true
t.index ["reset_password_token"], name: "index_candidates_on_reset_password_token", unique: true
end
I tried
<head>
<script>$( "#user_organization_name" ).keypress(function() {
$('#custom_org_id_select_menu').removeClass();
});</script>
</head>
<h2>Sign up for candidates</h2>
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :email,
required: true,
autofocus: true,
placehoder: "name#gmail.com",
input_html: { autocomplete: "email" }%>
<%= f.input :password,
required: true,
hint: ("#{#minimum_password_length} characters minimum" if #minimum_password_length),
input_html: { autocomplete: "new-password" },
placeholder: "xYui6578Z!"%>
<%= f.input :password_confirmation,
required: true,
input_html: { autocomplete: "new-password" },
placeholder: "Repeat above password"%>
<div id="custom_org_id_select_menu">
<%= f.select(:skill, [['Python', 'Python'],
['Java', 'Java'],
['Rails', 'Rails'],
],
{ :multiple => true, :size => 5 }
) %>
</div>
<div id="custom_org_id hide">
<%= f.input :skill, label: "Others" %>
</div>
It does work, but if the users writes something in other and selects something from the list (python, java etc), only what the user writes in other is sent via the params.
You can create a basic param for other skill and use it in the create action, like:
<div id="custom_org_id_select_menu">
<%= f.select(:skill, [['Python', 'Python'], ['Java', 'Java'], ['Rails', 'Rails']],{ :multiple => true, :size => 5 }) %>
</div>
<div id="custom_org_id hide">
<label>Others</label>
<input name="other_skill" />
</div>
def create
if params[:other_skill].present?
# do something with the params[:other_skill] value
end
#...
end

Rails 5: find_or_create_by not saving all the params

I have a form that should send info. One of the inputs is "empresa_id", and it's represented by a collection. I have checked in the server the form send the information I want. The thing is this field (only that one) is not saved when I run find_or_create_by. I've checked strong params and everything seem fine there.
SuscriptorsController
def create
#suscriptor = Suscriptor.new(suscriptor_params)
byebug #In this point #suscriptor.empresa_id has a correct value
if !#suscriptor.valid?
flash[:error] = "El email debe ser válido"
render 'new'
else
#suscriptor = Suscriptor.find_or_create_by(email: #suscriptor.email)
if #suscriptor.persisted?
if (#suscriptor.email_confirmation == true)
flash[:notice] = "Ya estás registrado/a"
redirect_to root_path
else
SuscriptorMailer.registration_confirmation(#suscriptor).deliver
end
else
flash[:error] = "Ha ocurrido un error. Contáctanos desde la sección contacto y explícanos"
render 'new'
end
end
private
def suscriptor_params
params.require(:suscriptor).permit(:email, :email_confirmation, :token_confirmation, :subtitle, :empresa_id)
end
Form view
<%= simple_form_for(#suscriptor) do |f| %>
<div class="input-group">
<div class="col-md-12">
<div class="form-group text">
<%= f.input :email, class: "form-control", placeholder: "tucorreo#email.com", required: true %>
<%= f.invisible_captcha :subtitle %>
<small id="emailHelp" class="form-text text-muted">Lo guardaremos y usaremos con cuidado.</small>
<%= f.input :empresa_id, collection: Empresa.all %>
</div>
<div class="input-group-append">
<%= f.submit "¡Hecho!", class: "btn btn-primary" %>
</div>
</div>
<% end %>
schema.rb
create_table "suscriptors", force: :cascade do |t|
t.string "email"
t.boolean "email_confirmation"
t.string "token_confirmation"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "empresa_id"
end
suscriptor.rb
class Suscriptor < ApplicationRecord
belongs_to :empresa, optional: true
before_create :confirmation_token
attr_accessor :subtitle
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, format: { with: VALID_EMAIL_REGEX }
def confirmation_token
if self.token_confirmation.blank?
self.token_confirmation = SecureRandom.urlsafe_base64.to_s
end
end
end
In your find_or_create_by, your pass only the #suscriptor.email, and reassing the #suscriptor variable with the created suscriptor.
According API dock, you should pass a block to 'create with more parameters':
Suscriptor.find_or_create_by(email: #suscriptor.email) do |suscriptor|
suscriptor.empresa_id = #suscriptor.empresa_id
end
Be careful to not reassign #suscriptor variable before use the parameters.
You can read more about find_or_create_by in https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by
Hope this helps!

adding row to table through form

I am trying to create a form that will add a row to my table but I am getting this error and I am not sure why:
Started POST "/test" for ::1 at 2014-11-30 01:51:49 -0800
Processing by UsersController#create as JS
Parameters: {"utf8"=>"✓", "users"=>{"first_name"=>"brady", "last_name"=>"LIII", "email"=>"brad#gmail.com", "phone_number"=>"123456789"}, "commit"=>"Save Users"}
Completed 500 Internal Server Error in 1ms
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/users_controller.rb:32:in `create'
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/_source.erb (2.0ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/_trace.text.erb (0.9ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/_request_and_response.text.erb (0.5ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/diagnostics.text.erb (11.5ms)
::1 - - [30/Nov/2014:01:51:49 -0800] "POST /test HTTP/1.1" 500 92618 0.0449
My form:
<!-- contact -->
<section id="contact">
<div class="container">
<div class="title-container">Contact Us</div>
<div class="title-caption">Reach us at (415)-911-9999</div>
<%= form_for(:users, remote: true, id: "contact-form", class: "contact-input") do |f| %>
<div class="col-md-12">
<div class="col-md-6">
<div class="contact-input-margin form-group">
<%= f.text_field(:first_name, class: "form-control", placeholder: "First name")%>
</div>
<div class="contact-input-margin form-group">
<%= f.text_field(:last_name, class: "form-control", placeholder: "Last name") %>
</div>
<div class="contact-input-margin form-group">
<%= f.email_field(:email, class: "form-control", placeholder: "Email") %>
</div>
<div class="contact-input-margin form-group">
<%= f.telephone_field(:phone_number, class: "form-control", placeholder: "Phone number") %>
</div>
</div>
</div>
<%= f.submit(class: "btn btn-xl") %>
<% end %>
</div>
</section>
My controller:
class UsersController < ApplicationController
def new
end
def create
if !(User.find_by(email: params[:user][:email]))
#user = User.new(user_params)
#user.save
end
end
private
def user_params
params.require(:users).permit(:first_name, :last_name, :email, :phone_number)
end
end
my user model
class User < ActiveRecord::Base
before_save { |user| user.email = user.email.downcase }
has_many :contact_requests
validates(:first_name, presence: true)
validates(:last_name, presence: true)
validates(:email, presence: true)
accepts_nested_attributes_for :contact_requests
end
my routes
Rails.application.routes.draw do
root 'home#index'
get 'test', to: "users#new"
post 'test', to: "users#create"
schema:
ActiveRecord::Schema.define(version: 20141130075753) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "contact_requests", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "message", null: false
t.integer "user_id"
end
add_index "contact_requests", ["user_id"], name: "index_contact_requests_on_user_id", using: :btree
create_table "users", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name", null: false
t.string "last_name", null: false
t.string "email", null: false
t.string "phone_number"
end
end

how to insert multi textbox array in ruby on rails

I'm new to ruby. i need insert the array textbox values to has_many and belongs_to relationship.i used two models intrrattes and intrsetups.
here is my new.html.erb file
<%= form_for #intrsetup do |f| %>
<div class='row'>
<div class='span6'>
<div class="control-group">
<label class=" control-label">Effective From<abbr title="required">*</abbr></label>
<div class="controls">
<%= f.text_field :effective_from, :onclick => "return calender()" %>
</div>
</div>
</div>
<div class='span6'>
<div class="control-group">
<label class=" control-label">Effective To</label>
<div class="controls">
<%= f.text_field :effective_to %>
</div>
</div>
</div>
</div>
<%= f.fields_for :intrrates do |builder| %>
<h3>Interest Rates</h3>
<table class='table condensed-table'>
<tr>
<td>
Days From
</td>
<td>
Days To
</td>
<td>
Rate
</td>
<td>
Senior Increment
</td>
<td>
Super Senior Increment
</td>
<td>
Widow Increment
</td>
</tr>
<tr>
<td>
<%(1..2).each do |i|%>
<%= builder.text_field(:days_from, :name => "intrrate[days_from][]", :id => "intrrate_days_from_#{i}") %>
<%end%>
<%= builder.text_field :days_to, multiple: true %>
<%= builder.text_field :rate, multiple: true %>
<%= builder.text_field :senior_increment %>
<%= builder.text_field :super_senior_increment %>
<%= builder.text_field :widow_increment %>
<% end %>
<%= f.submit %>
here is my Intrrate and Intrsetup model code
class Intrrate < ActiveRecord::Base
belongs_to :intrsetup
#attr_accessor :effective_from, :effective_to
attr_accessible :effective_from, :effective_to
attr_accessible :days_from, :days_to, :rate, :senior_increment, :super_senior_increment, :widow_increment, :intrsetup_id
end
class Intrsetup < ActiveRecord::Base
has_many :intrrates
accepts_nested_attributes_for :intrrates
attr_accessible :intrrates_id, :effective_from, :effective_to, :intrrates_attributes
end
here is my controller page
class IntrsetupsController < ApplicationController
def new
#intrsetup = Intrsetup.new
#intrrate = #intrsetup.intrrates.build
end
def create
#intrsetup = Intrsetup.new(params["intrsetup"])
#intrsetup.save
end
end
class IntrratesController < ApplicationController
def index
#intrrate = Intrrate.all
end
def new
#intrrate = Intrrate.new
end
def create
puts #intrrate = Intrrate.new(params["intrrate"])
#intrrate.save
end
end
my schema.rb
create_table "intrrates", :force => true do |t|
t.integer "days_from"
t.integer "days_to"
t.float "rate"
t.float "senior_increment"
t.float "super_senior_increment"
t.float "widow_increment"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "intrsetup_id"
t.integer "deposit_id"
end
create_table "intrsetups", :force => true do |t|
t.date "effective_from"
t.date "effective_to"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
my error page
NoMethodError in IntrsetupsController#create
undefined method `[]' for nil:NilClass
Rails.root: /home/tbf/rails_projects/ccddeposit
Application Trace | Framework Trace | Full Trace
app/controllers/intrsetups_controller.rb:9:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"WsfTU31o9LLfcoieNL3pgpRRu/swqreaXDdo6LxrdsM=",
"intrsetup"=>{"effective_from"=>"1994/12/06",
"effective_to"=>"1994/12/06"},
"intrrate_days_from_1"=>"1",
"intrrate_days_to_1"=>"45",
"intrrate_rate_1"=>"0.5",
"intrrate_senior_increment_1"=>"0.5",
"intrrate_super_senior_increment_1"=>"0.56",
"intrrate_widow_increment_1"=>"0.5",
"intrrate_days_from_2"=>"45",
"intrrate_days_to_2"=>"95",
"intrrate_rate_2"=>"0.5",
"intrrate_senior_increment_2"=>"0.7",
"intrrate_super_senior_increment_2"=>"0.8",
"intrrate_widow_increment_2"=>"0.5",
"commit"=>"Create Intrsetup"}
but i'm getting the following error
how to solve this error?
As I said, the problem is rate is attending a float and you give to it an Array.
So here is a code which force your parameter "rate" as a float value and give you the average of all rates entered in your form :
def create
# In case where you want the average value of all different rates you enter in your form
rate_avg = params["intrsetup"]["intrrates_attributes"]["0"]["rate"].inject(0.0) do |value, rate|
value += rate.to_f
end
params["intrsetup"]["intrrates_attributes"]["0"]["rate"] = rate_avg / params["intrsetup"]["intrrates_attributes"]["0"]["rate"].count
#intrsetup = Intrsetup.new(params["intrsetup"])
#intrsetup.save
end
Try this and tell me if it works now.

Resources