adding provider to patient - ruby-on-rails

I am trying to add providers to patients list. For example patients can have many providers. It's not working. My code may be wrong but any help will be appreciated.
<% #providers.each do |provider| %>
<div class="item" data-email="<%=provider.role.user.email%>" data-name="<%=provider.role.user.first_name%> <%=provider.role.user.last_name%>">
<div class="d-inline-block">
<p class="name"><%= provider.role.user.first_name %><%= " " + provider.role.user.middle_name if provider.role.user.middle_name %><%= " " + provider.role.user.last_name %></p>
<p class="name"><span>Professional Title: </span><%= provider.professional_title if provider.professional_title %></p>
</div>
<div class="d-inline-block float-right">
<%= link_to patient_add_provider_path(#patient, provider_join: #patient.id, provider_id: provider.id), method: :post, :data => {:confirm => 'Are you sure you want to add this site?'} do %> ####THIS IS WHAT CURRENTLY IS NOT WORKING(link_to)
<button class="btn-submit">Add</button>
</div>
</div><!--item-->
<% end %>
Here is a the method i have inside my patient_controller.rb file
def add_provider
flash[:modal]
#patient = current_user.current_role.roleable
#provider = Provider.find(params[:provider_id])
#provider_join = Provider_join.where(
:provider_id => params[:provider_id]).first_or_create do |provider_join|
provider_join.provider = params[:provider_id]
end
#provider_join.soft_delete = false
if #provider_join.save
flash[:success] = "You have successfully added a physician to your list"
redirect_back(fallback_location: root_path)
else
end
end
and here is my schema file
create_table "provider_joins", id: false, force: :cascade do |t|
t.bigint "provider_id"
t.bigint "patient_id"
t.boolean "soft_delete", default: false
t.index ["patient_id"], name: "index_provider_joins_on_patient_id"
t.index ["provider_id"], name: "index_provider_joins_on_provider_id"
end
and finally but not least here is the error i am receiving in the console
ActionView::Template::Error (undefined method `id' for nil:NilClass):
6: </div>
7:
8: <div class="d-inline-block float-right">
9: <%= link_to patient_add_provider_path(#patient, provider_join: #patient.id, provider_id: provider.id), method: :post, :data => {:confirm => 'Are you sure you want to add this Physician?'} do %>
10: <button class="btn-submit">Add</button>
11: <% end %>
12:

Related

rails filter boolean attribute

I need to add filter to my search form. I need my search can filter the place that has either 'toy' or 'high chair'. I'm little bit confuse how to create if else condition in controller if the user add one of the filter, both or none.
Places
t.string "name"
t.string "address"
t.float "latitude"
t.float "longitude"
t.bigint "user_id"
t.boolean "toy", default: false
t.boolean "high_chair", default: false
// Controller
def index
#places = policy_scope(Place)
#text_search = params[:search]
if #text_search.present?
#places = Place.global_search(params[:search]).where(type: #types).where(toy:
params[:toy].where(high_chair: params[high_chair])
else
#places = Place.all
#result = "No Result"
end
end
// View
<%= form_tag(places_path, method: :get, class: "search-form") do %>
<div class="search-input">
<%= text_field_tag :search, params[:search],
class: "search-input form-control",
placeholder: "Type your city...'"%>
<%#= check_box_tag(:toy) %>
<%#= label_tag(:toy, "Toys") %>
<%#= check_box_tag(:high_chair) %>
<%#= label_tag(:high_chair, "High Chair") %>
<%= submit_tag "🔎", class: "search-submit btn-search" %>
</div>
<% end %>
I suggest you use ransack gem, it would be easier.
// View
<%= search_form_for #query, url: places_path, method: :get, class: "search-form" do |f| %>
<%= f.label :high_chair_true %>
<%= f.check_box :high_chair_true %>
<%= f.label :high_chair_false %>
<%= f.check_box :high_chair_false %>
<%= f.label :toy_true %>
<%= f.check_box :toy_true %>
...
<%= f.submit "search" %>
<% end %>
// Controller
def index
#query = Place.ransack(params[:query])
#places = #query.result
end
play with the combinations to fit your needs.

Rails 5 - Nested attributes in form, params missing or empty

I am trying to create two associated objects from two different models but I am still getting the same error "param is missing or the value is empty: repost" I have tried to figure out why it fails for days but in vain. Any hint?
I have the Model repost
class Repost < ApplicationRecord
has_many :recurrences, inverse_of: :repost
accepts_nested_attributes_for :recurrences
def self.create_repost (twit_id)
twit = Twit.find_by_id(twit_id)
Repost.find_or_create_by(link: twit.link) do |repost|
repost.twit_id = twit.id
repost.content = twit.content
repost.image_url = twit.image_url
repost.content_url = twit.content_url
repost.click = 0
repost.like = 0
repost.retweet = 0
repost.engagement = 0
repost.number_of_publications = repost.publications.count
repost.likes_sum = 0
repost.retweets_sum = 0
repost.engagement_sum = 0
repost.recurrence = repost.recurrences.recurring
end
end
and the model Recurrence
class Recurrence < ApplicationRecord
serialize :recurring, Hash
belongs_to :repost, inverse_of: :recurrences
def self.set(repost_id, frequency)
repost = Repost.find_by_id(repost_id)
Recurrence.create do |recurrence|
recurrence.repost_id = repost.id
recurrence.recurring = frequency
recurrence.start_time = recurrence.created_at
recurrence.end_time = nil
end
end
def recurring=(value)
if RecurringSelect.is_valid_rule?(value)
super(RecurringSelect.dirty_hash_to_rule(value).to_hash)
else
super(nil)
end
end
def rule
rule = IceCube::Rule.from_hash(self.recurring)
rule
end
def schedule
schedule = IceCube::Schedule.new(self.created_at)
schedule.add_recurrence_rule(rule)
schedule
end
end
here is my Repost Controller
class RepostsController < ApplicationController
before_action :find_repost, only: [:show, :edit, :update, :destroy, :get_likes]
def index
#repost = Repost.new
if params[:filter_by]
#reposts = Repost.filter(params[:filter_by], params[:min], params[:max], params[:start_at], params[:end_at])
else
#reposts = Repost.all.order("created_at DESC")
end
end
def show
end
def new
#repost = Repost.new
end
def create
#repost = Repost.create_repost(repost_params)
redirect_to reposts_path
end
def destroy
#repost.destroy
redirect_to reposts_path
end
private
def find_repost
#repost = Repost.find(params[:id])
end
def repost_params
params.require(:repost).permit(:twit_id, recurrences_attributes: [:recurring])
end
end
and here is my view with the form
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">
<h1 class="twit-h1">My best Tweets</h1>
<p><%= render "filter_form" %></p>
<p><% #twits.each do |twit| %></p>
<p><%= form_for #repost do |f| %></p>
<%= hidden_field_tag :twit_id , twit.id %>
<div class="twit">
<%= image_tag "#{twit.image_url}", class: "twit-image" %>
<div class="twit-body">
<% if twit.content.present? %>
<h3><%= twit.content %></h3>
<% else %>
<%= "This tweet has no text" %>
<% end %>
<% if twit.content_url.present? %>
<%= link_to "#{twit.content_url}".truncate(40), twit.content_url, class: "twit-link" %>
<% else %>
<%= "This tweet has no link" %>
<% end %>
<%= f.fields_for :recurrences do |r| %>
<h6 style="float: right;"><%= r.select_recurring :recurring %></h6>
<% end %>
<h6>
<i class="fa fa-bullhorn fa" aria-hidden="true"></i> <%= twit.engagement %>
<i class="fa fa-retweet fa" aria-hidden="true"></i> <%= twit.retweet %>
<i class="fa fa-heart fa" aria-hidden="true"></i> <%= twit.like %>
</h6>
<p>Tweeted on <%= (twit.first_date).strftime("%A, %B %d, %Y at %I:%M%p %Z") %></p>
<%= link_to "Delete", twit_path(twit), name: nil, class: "btn btn-danger btn-sm", method: :delete, data: {:confirm => 'Are you sure?'} %>
<%= f.submit "Add to your Reposts library", class: "btn btn-primary btn-sm" %>
<% end %>
</div>
</div>
<% end %>
</div>
</div>
</div>
Update, here is my logs
Started POST "/__better_errors/923b59f8da1318ef/variables" for ::1 at 2017-02-21 15:52:56 +0100
Started POST "/reposts" for ::1 at 2017-02-21 15:54:14 +0100
Processing by RepostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"62pE3le5m99HF10RgQcd70wFHqWQWiRmQQO2ndNHT3gnceRu94Y1ttyBuSExBjr4/cxeVUtgY60GRThxdpFGJg==", "twit_id"=>"1844", "recurring"=>"{\"interval\":1,\"until\":null,\"count\":null,\"validations\":{\"day\":[1],\"hour_of_day\":1,\"minute_of_hour\":0},\"rule_type\":\"IceCube::WeeklyRule\",\"week_start\":0}", "commit"=>"Add to your Reposts library"}
Completed 400 Bad Request in 2ms (ActiveRecord: 0.0ms)
ActionController::ParameterMissing - param is missing or the value is empty: repost:
It seems my error comes from this private method in my Repost controller but I can't understand why?
def repost_params
params.require(:repost).permit(:twit_id, recurrences_attributes: [:recurring])
end
Thank you!

Rails Multi-step form

I'm writing a quiz app with rails 5. I have got a multi-step form for question building.
Models:
class Mcq < ApplicationRecord
attr_accessor :option_count
has_many :options, dependent: :destroy
belongs_to :quiz
accepts_nested_attributes_for :options
validates :question_text, presence: true
end
class Option < ApplicationRecord
belongs_to :mcq, optional: true
validates :option_text, presence: true
end
Schema:
create_table "mcqs", force: :cascade do |t|
t.string "question_text"
t.boolean "required"
t.boolean "multiselect"
t.integer "quiz_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "options", force: :cascade do |t|
t.string "option_text"
t.integer "mcq_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
The first page is for question setup and has the following fields:
Option Count
Required (Yes / No)
No of options that can be selected (Single / Multiple)
The second page is for options and has the following fields:
Question Text
Nested Form for Options
Controller:
class McqsController < ApplicationController
def new
session[:current_step] ||= 'setup'
session[:mcq_params] ||= {}
#current_step = session[:current_step]
#quiz = Quiz.find(params[:quiz_id])
#mcq = Mcq.new(session[:mcq_params])
if session[:current_step] == 'options'
#option_count = session[:mcq_params]['option_count']
#option_count.times { #mcq.options.build }
end
end
def create
if params[:previous_button]
session[:current_step] = 'setup'
redirect_to new_quiz_mcq_path
elsif session[:current_step] == 'setup'
save_session(params[:mcq])
redirect_to new_quiz_mcq_path
elsif session[:current_step] == 'options'
#mcq = Mcq.new(whitelisted_mcq_params)
#mcq.quiz_id = params[:quiz_id]
#quiz = Quiz.find(params[:quiz_id])
if #mcq.save
session[:current_step] = session[:mcq_params] = nil
redirect_to quiz_new_question_path(#mcq.quiz_id)
else
#current_step = session[:current_step]
render :new
end
end
end
private
def whitelisted_mcq_params
params.require(:mcq)
.permit(:question_text, :multiselect, :required, options_attributes: [:option_text])
end
def save_session(mcq_params)
session[:mcq_params][:option_count] = mcq_params[:option_count].to_i
session[:mcq_params][:required] = mcq_params[:required]
session[:mcq_params][:multiselect] = mcq_params[:multiselect]
session[:current_step] = 'options'
end
end
The above solution works, but the code is messy and difficult to understand. I came across this railscasts episode which does something similar in a cleaner way. I've updated my code as follows:
class Mcq < ApplicationRecord
has_many :options, dependent: :destroy
belongs_to :quiz
attr_writer :current_step
attr_accessor :option_count
accepts_nested_attributes_for :options
validates :question_text, presence: true
def current_step
#current_step || steps.first
end
def steps
%w[setup options]
end
def next_step
self.current_step = steps[steps.index(current_step)+1]
end
def previous_step
self.current_step = steps[steps.index(current_step)-1]
end
def last_step?
current_step == steps.last
end
end
class McqsController < ApplicationController
def new
session[:mcq_params] ||= {}
#quiz = Quiz.find(params[:quiz_id])
#mcq = Mcq.new(session[:mcq_params])
#mcq.current_step = session[:mcq_step]
end
def create
#quiz = Quiz.find(params[:quiz_id])
session[:mcq_params].deep_merge!(params[:mcq]) if params[:mcq]
#mcq = Mcq.new(session[:mcq_params])
#option_count = session[:mcq_params]['option_count']
#option_count.times { #mcq.options.build }
#mcq.quiz_id = params[:quiz_id]
#mcq.current_step = session[:mcq_step]
if params[:previous_button]
#mcq.previous_step
elsif #mcq.last_step?
#mcq.save if #mcq.valid?
else
#mcq.next_step
end
session[:mcq_step] = #mcq.current_step
if #mcq.new_record?
render "new"
else
session[:mcq_step] = session[:mcq_params] = nil
redirect_to edit_quiz_path(#mcq.quiz_id)
end
end
end
But each time the second page is shown, the no of fields for options doubles or in case of invalid entry only the field for question_text is shown. How do I show the options correctly? Should I just go with my first solution? I'm new to rails and don't know much about the best practices.
Edited :
new.html.erb
<div class="sub-heading">Add a Multiple Choice Question:</div>
<%= render "mcq_#{#mcq.current_step}", quiz: #quiz, mcq: #mcq %>
_mcq_setup.html.erb
<div class="form-container">
<%= form_for [quiz, mcq] do |f| %>
<div class="form-row">
<div class="response-count">How many options should the question have?</div>
<%= f.select(:option_count, (2..5)) %>
</div>
<div class="form-row">
<div class="response-count">How many options can be selected?</div>
<div class="option">
<%= f.radio_button :multiselect, 'false', checked: true %>
<%= f.label :multiselect, 'Just One', value: 'false' %>
</div>
<div class="option">
<%= f.radio_button :multiselect, 'true' %>
<%= f.label :multiselect, 'Multiple', value: 'true' %>
</div>
</div>
<div class="form-row">
<div class="response-count">Is the question required?</div>
<div class="option">
<%= f.radio_button :required, 'true', checked: true %>
<%= f.label :required, 'Yes', value: 'true' %>
</div>
<div class="option">
<%= f.radio_button :required, 'false' %>
<%= f.label :required, 'No', value: 'false' %>
</div>
</div>
<%= f.submit "Continue to the Next Step" %>
<% end %>
</div>
_mcq_options.html.erb
<%= form_for [quiz, mcq] do |f| %>
<%= f.label :question_text, 'What is your question?' %>
<%= f.text_field :question_text %>
<%= f.fields_for :options do |option_fields| %>
<%= option_fields.label :option_text, "Option #{option_fields.options[:child_index] + 1}:" %>
<%= option_fields.text_field :option_text %>
<% end %>
<%= f.hidden_field :multiselect %>
<%= f.hidden_field :required %>
<%= f.submit "Add Question" %>
<%= f.submit "Back to previous step", name: 'previous_button' %>
<% end %>
You may look in direction of state_machine. By using that you can use your steps as states of state machine and use its ability to define validations that only active for given states (look here in state :first_gear, :second_gear do) so fields that required on second step will be not required on first. Also, it'll allow you to avoid complex checks for the step you currently on (because the state will be persisted in a model) and will be pretty easy to extend with more steps in a future.

Survey App Using Nested Models, Partials, & Rails Form Builder

I extracted this code from the following engine:
Link to Demo:
https://rapidfire.herokuapp.com/rapidfire/question_groups/1110/answer_groups/new
Link to Code:
https://github.com/code-mancers/rapidfire/blob/master/app/services/rapidfire/answer_group_builder.rb
I trying to modify it so that I can create custom answer types, called "kind"(s) (see schema). One kind called "indicator" (see _indicator.html.erb), has multiple columns.
My models are setup as follows:
Survey
has_many :question_groups
accepts_nested_attributes_for :question_groups
end
QuestionGroup
belongs_to :survey
has_many :questions
accepts_nested_attributes_for :questions
end
AnswerGroup
belongs_to :survey
has_many :answers
accepts_nested_attributes_for :answers
end
Answer
belongs_to :question
belongs_to :answer_group, inverse_of: :answers
end
Question 1: What does this line do? (see build_answer_group method)
#answers = question_group.questions.collect do |question|
In the console,
#answers = [#<Answer id: nil, answer_group_id: nil, question_id: 1034,
answer_text: nil, created_at: nil, updated_at: nil>, #<Answer id: nil,
answer_group_id: nil, question_id: 1035, answer_text: nil, created_at: nil,
updated_at: nil>]
question_ids 1034 and 1035 refer to the last items in the array produced by
question_group.questions
Instead, I need #answers to be the Answer class equivalent of all questions.
Why is it returning only two items?
Question 2:
For the indicator partial, I need to display the name of the Question Group and the names of each subitem, e.g. "Questions", and five additional columns with unique html names and ids. So, if I had two question groups of kind "indicator", I need to produce something like:
QuestionGroup1.name
id = answer_group_1034_answer_text name = answer_group[1034][answer_text]
id = answer_group_1035_answer_text name = answer_group[1035][answer_text]
etc...
QuestionGroup2.name
id = answer_group_1036_answer_text name = answer_group[1036][answer_text]
id = answer_group_1037_answer_text name = answer_group[1037][answer_text]
Currently, it is producing:
For QuestionGroup1:
<textarea rows="5" name="answer_group[1034][answer_text]"
id="answer_group_1034_answer_text"></textarea>
<textarea rows="5" name="answer_group[1034][answer_text]"
id="answer_group_1034_answer_text"></textarea>
For QuestionGroup2:
<textarea rows="5" name="answer_group[1035][answer_text]"
id="answer_group_1034_answer_text"></textarea>
<textarea rows="5" name="answer_group[1035][answer_text]"
id="answer_group_1034_answer_text"></textarea>
Goal: Assign a unique id and name for each row within a question group for the indicator partial
views/answer_groups/_fidelitychecklist.html.erb
<%= form_for([#survey, #answer_group_builder]) do |f| %>
<% #answer_group_builder.answers.each do |answer| %>
<%= f.fields_for("#{answer.question.id}", answer) do |answer_form| %>
<%= render_answer_form_helper(answer, answer_form) %>
<% end %>
<% end %>
<%= f.submit "Save" %>
<% end %>
services/answer_group_builder.rb
class AnswerGroupBuilder < BaseService
attr_accessor :user, :survey, :questions, :answers, :params
def initialize(params = {})
super(params)
build_answer_group
end
def to_model
#answer_group
end
...
private
def build_answer_group
#answer_group = AnswerGroup.new(user: user, survey: survey)
#survey.question_groups.each do |question_group|
#answers = question_group.questions.collect do |question|
#answer_group.answers.build(question_id: question.id)
end
end
end
AnswerGroupsController
before_filter :find_survey!
def new
#answer_group_builder = AnswerGroupBuilder.new(answer_group_params)
end
def create
#answer_group_builder = AnswerGroupBuilder.new(answer_group_params)
if #answer_group_builder.save
redirect_to surveys_path
else
render :new
end
end
private
def find_survey!
#survey = Survey.find(params[:survey_id])
end
def answer_group_params
answer_params = { params: params[:answer_group] }
answer_params.merge(user: current_user, survey: #survey)
end
module ApplicationHelper
def render_answer_form_helper(answer, form)
partial = Question.where(id: answer.question_id).last.question_group.kind.to_s
questiongroup = Question.find(answer.question_id).question_group
render partial: "/answers/#{partial}", locals: {f: form, answer: answer, questiongroup: questiongroup }
end
views/answers/_indicator.html.erb
<%= render partial: "answers/errors", locals: {answer: answer} %>
<fieldset>
<table class="indicator">
<thead>
<th class="first head-row">Indicators</th>
<th class="head-row">Presence</th>
<th class="head-row">Rating</th>
<th class="head-row">Element(s) Implemented Well</th>
<th class="head-row">Element(s) Requiring Further Support</th>
<th class="head-row">Comments/Action Steps</th>
</thead>
<tbody>
<tr><td colspan="6" class="indicator-title"><%= questiongroup.name %></td></tr>
<% questiongroup.questions.each do |question| %>
<tr>
<td class="first row">
<%= question.question_text %>
</td>
<td class="row">
<%= f.select :answer_text, options_for_select([["N/O", "n/o"], ["N", "n"]]) %>
</td>
<td class="row">
<%= f.select :answer_text, options_for_select([["1", "1"], ["2", "2"], ["3", "3"]]) %>
</td>
<td class="row">
<%= f.text_area :answer_text, rows: 5 %>
</td>
<td class="row">
<%= f.text_area :answer_text, rows: 5 %>
</td>
<td class="row">
<%= f.text_area :answer_text, rows: 5 %>
</td>
</tr>
<% end %>
</tbody>
</table>
</fieldset>
schema.rb
create_table "surveys", force: :cascade do |t|
t.string "name", limit: 255
end
create_table "question_groups", force: :cascade do |t|
t.string "name", limit: 255
t.integer "position", limit: 4
t.integer "survey_id", limit: 4
t.text "kind", limit: 65535
end
create_table "questions", force: :cascade do |t|
t.string "question_text", limit: 255
t.integer "position", limit: 4
t.integer "question_group_id", limit: 4
end
create_table "answer_groups", force: :cascade do |t|
t.integer "survey_id", limit: 4
end
create_table "answers", force: :cascade do |t|
t.integer "answer_group_id", limit: 4
t.integer "question_id", limit: 4
t.text "answer_text", limit: 65535
end
routes.rb
resources :surveys do
resources :answer_groups, only: [:new, :create] do
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