Not able to create funding table for multiple children - ruby-on-rails

each child can apply for funding. But when I apply for funding it always created funding application for Child_id:1 even if I am applying for some other child. funding belongs to child and children can have many fundings. please help
fundings_controller.rb
def create
#funding = Funding.new(funding_params)
#funding.child = Child.find(child_user.ids[0])
if #funding.save
flash[:success] = "Thankyou for submitting"
redirect_to funding_path(#funding)
else
render 'new'
end
end
application_controller.rb
def current_user
#current_user ||= Family.find(session[:family_id]) if session[:family_id]
end
def parent_user
#parent_user ||= Parent.find(session[:family_id]) if session[:family_id]
end
def child_user
puts session[:family_id]
#child_user ||= Child.where(:parent_id=>session[:family_id]).limit(1) if session[:family_id]
end
funding.rb
class Funding < ApplicationRecord
has_many :organisations
accepts_nested_attributes_for :organisations, reject_if: :all_blank, allow_destroy: true
belongs_to :child
end
child.rb
class Child < ApplicationRecord
belongs_to :parent
has_many :fundings
validates :parent_id, presence: true
validates :firstname, presence: true
validates :lastname, presence: true
validates :dateofbirth, presence: true
end
parent.rb
class Parent < ApplicationRecord
has_many :children, dependent: :destroy
has_many :secondaryparents, dependent: :destroy
accepts_nested_attributes_for :secondaryparents, reject_if: :all_blank, allow_destroy: true
belongs_to :family
validates :parent_1_firstname, presence: true
validates :parent_1_lastname, presence: true
validates :address, presence: true
validates :city, presence: true
validates :telephone_number, presence: true
validates :postal_code, presence: true
validates :email, presence: true
validates :family_id, presence: true
end
family.rb
class Family < ApplicationRecord
has_many :parents, dependent: :destroy
before_save { self.email = email.downcase }
VALID_EMAIL_REGEX = /\A[A-Za-z0-9.]+#[A-Za-z0-9]+\.[A-Za-z]+\z/i
validates :email, presence: true, uniqueness: {case_sensitive: false}, format: { with: VALID_EMAIL_REGEX }
has_secure_password
end
Parent
_form.html.erb
<%= render 'shared/errors', obj: #parent %>
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#parent, :html => {class: "form-horizontal", role: "form"}) do |f| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :parent_1_firstname %>
</div>
<div class="col-sm-8">
<%= f.text_field :parent_1_firstname, class: "form-control", placeholder: "Parent 1 first name", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :parent_1_lastname %>
</div>
<div class="col-sm-8">
<%= f.text_field :parent_1_lastname, class: "form-control", placeholder: "Parent 1 last name", autofocus:true %>
</div>
</div>
<p><strong>Add Secondary Parents or Guardians<br /></strong></p>
<div id ='secondaryparents'>
<%= f.fields_for :secondaryparents do |builder| %>
<%= render 'secondaryparent_fields', :f => builder %>
<% end %>
<%= link_to_add_association 'Add Secondary Parent', f, :secondaryparents %>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :address %>
</div>
<div class="col-sm-8">
<%= f.text_area :address, class: "form-control", placeholder: "Address", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :city %>
</div>
<div class="col-sm-8">
<%= f.text_field :city, class: "form-control", placeholder: "City", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :province %>
</div>
<div class="col-sm-8">
<%= f.text_field :province, class: "form-control", placeholder: "Province", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :telephone_number %>
</div>
<div class="col-sm-8">
<%= f.text_field :telephone_number, class: "form-control", placeholder: "Telephone Number", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :postal_code %>
</div>
<div class="col-sm-8">
<%= f.text_field :postal_code, class: "form-control", placeholder: "Postal code", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :email %>
</div>
<div class="col-sm-8">
<%= f.text_field :email, value: current_user.email, class: "form-control", placeholder: "Email", readonly:true, autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :family_situation %>
</div>
<div class="col-sm-8">
<%= f.text_area :family_situation, class: "form-control", placeholder: "Family Situation", autofocus:true %>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<%= f.submit class: 'btn btn-primary btn-lg' %>
</div>
</div>
<% end %>
</div>
</div>
children
_form.html.erb
<%= render 'shared/errors', obj:#child %>
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#child, :html => {class: "form-horizontal", role: "form"}) do |form| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :firstname %>
</div>
<div class="col-sm-8">
<%= form.text_field :firstname, class: "form-control", placeholder: "Enter child's first name", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :lastname %>
</div>
<div class="col-sm-8">
<%= form.text_field :lastname, class: "form-control", placeholder: "Enter child's last name", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :dateofbirth %>
</div>
<div class="col-sm-8">
<%= form.date_field :dateofbirth, class: "form-control", placeholder: "Date of Birth", autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :gender %>
</div>
<div class="col-sm-8">
<%= form.select :gender, ['Male', 'Female', 'Other'], class: "form-control", placeholder: "Gender", autofocus:true %>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<%= form.submit(#child.new_record? ? "Add your child" : "Update your child ", class: 'btn btn-primary btn-lg') %>
</div>
</div>
</div>
</div>
<% end %>
funding _form.html.erb
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#funding, :html => {class: "form-horizontal",role: "form"}) do |form| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :type_of_activity %>
</div>
<div class="col-sm-8">
<%= form.select :type_of_activity, ['Swimming', 'Soccer', 'Cricket', 'Basket Ball'] %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :describe_activity %>
</div>
<div class="col-sm-8">
<%= form.text_area :describe_activity %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :season %>
</div>
<div class="col-sm-8">
<%= form.select :season, ['Fall', 'Winter', 'Summer'], autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :activity_details %>
</div>
<div class="col-sm-8">
<%= form.text_area :activity_details %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :name_of_organisation %>
</div>
<div class="col-sm-8">
<%= form.select :name_of_organisation, ['BCCI', 'IPL', 'Sahara', 'Not listed'], class: "form-control", autofocus:true %>
</div>
</div>
<div id ='Organisations'>
<%= form.fields_for :organisations do |builder| %>
<%= render 'organisation_fields', :form => builder %>
<% end %>
<%= link_to_add_association 'Add Organisation', form, :organisations, form_name: 'form' %>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :activity_start_date %>
</div>
<div class="col-sm-8">
<%= form.date_field :activity_start_date %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :number_of_weeks %>
</div>
<div class="col-sm-8">
<%= form.text_field :number_of_weeks %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :days_per_week %>
</div>
<div class="col-sm-8">
<%= form.text_field :days_per_week %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :hours_per_day %>
</div>
<div class="col-sm-8">
<%= form.text_field :hours_per_day %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :program_registration_cost %>
</div>
<div class="col-sm-8">
<%= form.text_field :program_registration_cost %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :family_contribution %>
</div>
<div class="col-sm-8">
<%= form.text_field :family_contribution %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :other_funds %>
</div>
<div class="col-sm-8">
<%= form.text_field :other_funds %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :other_fund_provider %>
</div>
<div class="col-sm-8">
<%= form.text_field :other_fund_provider %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :amount_requested %>
</div>
<div class="col-sm-8">
<%= form.text_field :amount_requested %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :status %>
</div>
<div class="col-sm-8">
<%= form.select :status, ['Pending', 'Approved', 'Declined'], class: "form-control", autofocus:true %>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<%= form.submit "Apply", class: 'btn btn-primary btn-lg' %>
</div>
</div>
</div>
</div>
<% end %>

Since a parent can only apply for funding for one child at a time, let them choose which child in the funding form, and pass in the :child_id as part of the funding parameters to the FundingsController#create action.
fundings_controller.rb:
def create
#funding = Funding.new(funding_params)
if #funding.save
flash[:success] = "Thankyou for submitting"
redirect_to funding_path(#funding)
else
render 'new'
end
end
application_controller.rb
def current_user
#current_user ||= Family.find(session[:family_id]) if session[:family_id]
end
def parent_user
#parent_user ||= Parent.find(session[:family_id]) if session[:family_id]
end
def current_children
puts session[:family_id]
#current_children ||= Child.where(:parent_id => parent_user.id) if session[:family_id]
end
helper_method :current_children
funding_form.html.erb
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#funding, :html => {class: "form-horizontal",role: "form"}) do |form| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label(:child_id, "Select child") %>
</div>
<div class="col-sm-8">
<%= form.select :child_id, options_for_select(current_children.map{|c| [c.firstname, c.id]}) %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :type_of_activity %>
</div>
<div class="col-sm-8">
<%= form.select :type_of_activity, ['Swimming', 'Soccer', 'Cricket', 'Basket Ball'] %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :describe_activity %>
</div>
<div class="col-sm-8">
<%= form.text_area :describe_activity %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :season %>
</div>
<div class="col-sm-8">
<%= form.select :season, ['Fall', 'Winter', 'Summer'], autofocus:true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :activity_details %>
</div>
<div class="col-sm-8">
<%= form.text_area :activity_details %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :name_of_organisation %>
</div>
<div class="col-sm-8">
<%= form.select :name_of_organisation, ['BCCI', 'IPL', 'Sahara', 'Not listed'], class: "form-control", autofocus:true %>
</div>
</div>
<div id ='Organisations'>
<%= form.fields_for :organisations do |builder| %>
<%= render 'organisation_fields', :form => builder %>
<% end %>
<%= link_to_add_association 'Add Organisation', form, :organisations, form_name: 'form' %>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :activity_start_date %>
</div>
<div class="col-sm-8">
<%= form.date_field :activity_start_date %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :number_of_weeks %>
</div>
<div class="col-sm-8">
<%= form.text_field :number_of_weeks %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :days_per_week %>
</div>
<div class="col-sm-8">
<%= form.text_field :days_per_week %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :hours_per_day %>
</div>
<div class="col-sm-8">
<%= form.text_field :hours_per_day %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :program_registration_cost %>
</div>
<div class="col-sm-8">
<%= form.text_field :program_registration_cost %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :family_contribution %>
</div>
<div class="col-sm-8">
<%= form.text_field :family_contribution %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :other_funds %>
</div>
<div class="col-sm-8">
<%= form.text_field :other_funds %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :other_fund_provider %>
</div>
<div class="col-sm-8">
<%= form.text_field :other_fund_provider %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :amount_requested %>
</div>
<div class="col-sm-8">
<%= form.text_field :amount_requested %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :status %>
</div>
<div class="col-sm-8">
<%= form.select :status, ['Pending', 'Approved', 'Declined'], class: "form-control", autofocus:true %>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<%= form.submit "Apply", class: 'btn btn-primary btn-lg' %>
</div>
</div>
</div>
<% end %>
</div>

Looking at your models, this should be part of the database tables.
|Family |Parent |Child |Funding |Organisation |
|-------+----------+-----------+----------+--------------|
|id | id | id |id |id |
|-------+----------+-----------+----------+--------------|
| |family_id |parent_id |child_id |founding_id |
The problem I see is that when you create a new funding you can add just one child. But you got a collection then you limited to 1 to make it work.
But you are adding only the first child fetched for the current_user (.limit(1)).
What you should do is for each one of the children, belonging to the parents, belonging to the current_user (found in Family), you need to create a new funding.
But the code changes a lot. Removing .limit(1) to get all the children collection, scan the collection and create a funding for each children.
But I think you need to create a new action in a different controller for that.
Or, but I do not know your purpose, consider to use a different association, like has_and_belongs_to_many between Child and Funding.

Related

rails 6 save data to multiple tables from one controller

I'm still really new to rails. I have a site that allows tournament directors to host online registration. When they setup the registraiton form they can add custom fields for different section like basic info, division, etc. That part is working but when the user goes to the registraiton form, I am able to pull the fields into the form but I don't know how to save them to a separate table. I have a participants table and the custom fields are in a fields table.
When a user registers or edits their registraion info, how do I save the input for the custom fields into a separate table. I have a table called field_answers with participant_id, field_id and answer, but can't figure out how to save the answers from the participants_controler.
Below is the form for the basic section of the registraiton form. The #basic.each section is where the custom fields are being pulled in, and I'm guessing I'll need to give the fields unique names rather than just answer then save them but I don't know how to do that.
<%= form_with model: [#event, #participant], class: "shadow p-3 mb-3 rounded text-dark", local: true do |f| %>
<%= f.hidden_field :child_id, value: #cid %>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.hidden_field :event_id, value: #tID %>
<%= f.hidden_field :basic_complete, value: 1 %>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :first_name %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :first_name, class: 'form-control', value: #part.first_name, placeholder: "First name" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :last_name %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :last_name, class: 'form-control', value: #part.last_name, placeholder: "Last name" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :date_of_birth %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.date_field :dob, class: 'form-control', value: #part.dob, placeholder: "Date of Birth" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :gender %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<label class="main">Female
<%= f.radio_button :gender, "female", checked: true if #part.gender == "female" %>
<span class="w3docs"></span>
</label>
<label class="main">Male
<%= f.radio_button :gender, "male", checked: true if #part.gender == "male" %>
<span class="w3docs"></span>
</label>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :address1 %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :address1, class: 'form-control', value: #part.address1, placeholder: "Address 1" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :address2 %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :address2, class: 'form-control', value: #part.address2, placeholder: "Address 2" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :city %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :city, class: 'form-control', value: #part.city, placeholder: "City" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :state %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :state, class: 'form-control', value: #part.state, placeholder: "State" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :country %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :country, class: 'form-control', value: #part.country, placeholder: "Country" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :zip %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :zip, class: 'form-control', pattern: "[0-9]*", value: #part.zip, placeholder: "Postal Code" %>
</div>
</div>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label :phone %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :phone, class: 'form-control', pattern: "[0-9]{3}-[0-9]{3}-[0-9]{4}", maxlength: "12", value: #part.phone, placeholder: "Phone" %>
</div>
</div>
<% #basic.each do |b| %>
<div class="form-group row">
<div class="col-md-2 col-sm-12 col-form-label">
<%= f.label b.name %>:<span class="text-danger">*</span>
</div>
<div class="col-md-10 col-sm-12">
<%= f.text_field :answer, class: 'form-control' %>
<%= f.hidden_field :field_id, value: b.id %>
<%= f.hidden_field :event_id, value: #tID %>
</div>
</div>
<% end %>
<div class="form-group row">
<div class="col-md-8 col-sm-12"></div>
<div class="col-md-4 col-sm-12">
<%= f.submit "Register", class: "profile_btn" %>
</div>
</div>
<% end %>
Here is my participants_controller.rb:
class ParticipantsController < ApplicationController
before_action :event
before_action :participant, only: %i[create]
def new
#participant = #event.participants.new
if current_user
#user = User.find(current_user.id)
#children = #user.children
end
#basic = Field.where(event_id: #event.id, field_type: 'basic')
end
def create
byebug
if #participant.save
flash[:success] = 'Child was successfully created.'
#redirect_to edit_event_participant_path(#participant.id)
redirect_to "/events/#{#event.id}/participants/#{#participant.id}/edit?rt=#{#participant.child_id != nil ? 'child' : 'self'}&step=2"
else
byebug
flash[:notice] = #participant.errors.full_messages.join('<br />').html_safe
redirect_back(fallback_location: events_path)
end
end
def show
end
def edit
#participant = Participant.find(params[:id])
#child = Child.find(#participant.child_id)
#custom_basic = Field.find_by(event_id: #participant.event_id, field_type: 'basic')
end
def update
end
private
def event
#event = Event.find_by(id: params[:event_tourn_url])
end
def participant
#participant = event.participants.new(participant_params)
end
def participant_params
params.require(:participant).permit(:event_id, :user_id, :child_id, :first_name, :last_name, :dob, :gender, :address1, :address2, :city, :state, :country, :zip, :phone, :basic_complete)
end
end
I'd appreciate any help.
Edit:
I edited my participant_params in the controller to:
def participant_params
params.require(:participant).permit(:event_id, :user_id, :child_id, :first_name, :last_name, :dob, :gender,
:address1, :address2, :city, :state, :country, :zip, :phone,
participant_fields_attributes: [:id, :participant_id, :field_id, :answer])
end
And my participants model is:
class Participant < ApplicationRecord
belongs_to :event
has_many :participant_fields
accepts_nested_attributes_for :participant_fields
When I submit all the correct fields are added to the participants table but nothing to the participant_fields table. And in the logs I get Unpermitted
parameters: :answer, :field_id

Rails 5: Ways to validate forms

Working on a form:
<%= form_for(#contact, html: {multipart: true}) do |f| %>
<div class="card">
<div class="card-header">
<h2 class="display-5 main-text-blue text-center font-weight-bold">Add New Contact</h2>
</div>
<div class="card-body">
<div class="errors">
<% if #contact.errors.any? %>
<div class="alert alert-danger">
<h5 class="text-center mb-n1 pb-1"><i class="fa fa-exclamation-triangle text-danger"></i> Please correct the following errors: </h5>
</div>
<% end %>
</div>
<div class="form-group row">
<div class="col-md-5 mx-auto">
<div class="wrap" id="avatar-container">
<div class="valign-middle">
<div class="form-group">
<% if #contact.new_record? %>
<%= image_tag "100x100.png", class: "img-responsve img-preview" %>
<% else %>
<%= image_tag #contact.avatar, class: "img-responsve img-preview" %>
<% end %>
<label for="file" class="sr-only">Choose Image</label>
<%= f.file_field :contact_avatar, id: "file" %>
</div>
</div>
</div>
</div>
</div>
<div class="form-group row">
<%= f.label :name, class: "col-lg-2 col-form-label" %>
<div class="col-lg-10">
<%= f.text_field :name, class: "form-control #{'is-invalid' if has_error?(#contact, :name) }", id: "name", placeholder: "Name.." %>
<% if has_error?(#contact, :name) %>
<span class="text-danger">
<%= get_error(#contact, :name)%>
</span>
<% end %>
</div>
</div>
<div class="form-group row">
<%= f.label :email, class: "col-lg-2 col-form-label" %>
<div class="col-lg-10">
<%= f.text_field :email, class: "form-control #{'is-invalid' if has_error?(#contact, :email) }", id: "email", placeholder: "Email.." %>
<% if has_error?(#contact, :email) %>
<span class="text-danger">
<%= get_error(#contact, :email)%>
</span>
<% end %>
</div>
</div>
<div class="form-group row">
<%= f.label :mobile, class: "col-lg-2 col-form-label" %>
<div class="col-lg-10">
<%= f.text_field :mobile, class: "form-control #{'is-invalid' if has_error?(#contact, :mobile) }", id: "mobile", placeholder: "Mobile.." %>
<% if has_error?(#contact, :mobile) %>
<span class="text-danger">
<%= get_error(#contact, :mobile)%>
</span>
<% end %>
</div>
</div>
<div class="form-group row">
<%= f.label :phone, class: "col-lg-2 col-form-label" %>
<div class="col-lg-10">
<%= f.text_field :phone, class: "form-control #{'is-invalid' if has_error?(#contact, :phone) }", id: "phone", placeholder: "Phone.." %>
<% if has_error?(#contact, :phone) %>
<span class="text-danger">
<%= get_error(#contact, :phone)%>
</span>
<% end %>
</div>
</div>
<div class="form-group row">
<%= f.label :country, class: "col-lg-2 col-form-label" %>
<div class="col-lg-10">
<%= f.text_field :country, class: "form-control", id: "country", placeholder: "Country.." %>
</div>
</div>
<div class="form-group row">
<%= f.label :address, class: "col-lg-2 col-form-label" %>
<div class="col-lg-10">
<%= f.text_field :address, class: "form-control", id: "address", placeholder: "Address.." %>
</div>
</div>
<div class="form-row">
<%= f.label :location, class: "col-lg-2 col-form-label" %>
<div class="col-4">
<%= f.text_field :city, class: "form-control", id: "city", placeholder: "City.." %>
</div>
<div class="col-4">
<%= f.text_field :state, class: "form-control", id: "state", placeholder: "State.." %>
</div>
<div class="col-2">
<%= f.text_field :zip, class: "form-control", id: "zip", placeholder: "Zip.." %>
</div>
</div>
<div class="form-group row category-mt">
<%= f.label :category, class: "col-lg-2 col-form-label" %>
<div class="col-lg-5">
<%= f.collection_select :category_id, Category.all, :id, :name, { prompt: "Select Category" }, id: "category_select", class: "form-control #{'is-invalid' if has_error?(#contact, :category) }" %>
<% if has_error?(#contact, :category) %>
<span class="text-danger">
<%= get_error(#contact, :category)%>
</span>
<% end %>
</div>
<div class="col-lg-3">
<a class="btn btn-outline-secondary add-category-button btn-block mt-1" href="#" id="add-category-btn">Add Category</a>
</div>
</div>
<div class="form-group row" id="add-new-category">
<label class="col-lg-2 col-form-label" for="location">New Category:</label>
<div class="col-lg-10">
<div class="input-group">
<input id="new-category" name="new-category" class="form-control <%= 'is-invalid' if has_error?(#category, :name) %>" placeholder="Enter category name" type="text">
<% if has_error?(#category, :name) %>
<span class="text-danger">
<%= get_error(#category, :name)%>
</span>
<% end %>
<div class="input-group-append">
<button class="btn btn-outline-secondary category-btn" id="save-new-category-btn" type="button"><i class="fa fa-check"></i></button>
</div>
</div>
</div>
</div>
<div class="form-group row">
<%= f.label :note, class: "col-lg-2 col-form-label" %>
<div class="col-lg-10">
<%= f.text_area :note, class: "form-control", id: "note", placeholder: "Note..", rows: "3" %>
</div>
</div>
</div>
<div class="card-footer">
<%= f.submit "Save", class: "btn btn-primary border-button mb-3 ml-3", id: "save-btn" %>
<a class="btn btn-outline-secondary border-button mt-n3" data-dismiss="modal" href="#" id="cancel-btn">Cancel</a>
</div>
</div>
<% end %>
As you can see here I place some rails validation codes which already exist on contacts model. For instance:
<%= f.text_field :name, class: "form-control #{'is-invalid' if has_error?(#contact, :name) }", id: "name", placeholder: "name.." %>
Which will add the class is-invalid if there are any errors. And this also:
<% if has_error?(#contact, :phone) %>
<span class="text-danger">
<%= get_error(#contact, :phone)%>
</span>
<% end %>
Which will simply print the error text at the bottom if there's an error. Here's the helper codes for that:
def has_error?(resource, field)
resource.errors.messages[field].present?
end
def get_error(resource, field)
msg = resource.errors.messages[field]
field.to_s.capitalize + " " + msg.join(' and ') + '.'
end
So, basically I am working on two tables here: Contact and Category. So far what am I verifying on my form are mostly contacts. I have this feature here where in user can add NEW CATEGORY right on the spot via ajax which is a foreign key on the contacts table which can also be seen on the code above.
Now, on my understanding, I can also add a validation on models. So I tried to put some validation on my category:
validates :name, uniqueness: true
I was hoping that this will validate the uniqueness of the new category being output, meaning if the text (category name) already exist on the database it must prohibit it and throw an error. So what I did is I tried the following code to display the error:
<input id="new-category" name="new-category" class="form-control <%= 'is-invalid' if has_error?(#category, :name) %>" placeholder="Enter category name" type="text">
<% if has_error?(#category, :name) %>
<span class="text-danger">
<%= get_error(#category, :name)%>
</span>
<% end %>
And so I thought it will work however it just throw an error saying
undefined method errors' for nil:NilClass which is I thought it should work since I am using #category but then I realize it's a form for #contact.
Is there a better way to make this work and display the error on the add new category field? I am really stuck on this. I hope someone can help me.
You can get categories errors through f object
<% f.object.categories.each do |category| %>
<input id="new-category" name="new-category" class="form-control <%= 'is-invalid' if has_error?(category, :name) %>" placeholder="Enter category name" type="text">
<% if has_error?(category, :name) %>
<span class="text-danger">
<%= get_error(category, :name)%>
</span>
<% end %>
<% end %>

How to upload a file using the file_file_tag?

I want to upload file in form but do not want its field inside a model.
so using the file_filed_tag
at view:
<%= form_tag services_datainterchange_path, method: :post, remote: true do %>
<div class="row">
<div class="col-sm-3 col-md-3">
<div class="form-group">
<%= label_tag :file %>
<%= file_field_tag :file, required: true, class: "form-control", id: "upload_file" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= label_tag :name %>
<%= text_field_tag :name, nil, required: true, class: "form-control", id: "upload_file_name" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= label_tag :source_type %>
<%= select_tag :source_type, options_for_select(ApplicationRecord::SOURCE_TYPE), class: "form-control" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= label_tag :final_type %>
<%= select_tag :final_type, options_for_select(ApplicationRecord::FINAL_TYPE), class: "form-control" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= submit_tag "Submit", class: "btn btn-primary" %>
</div>
</div>
</div>
<% end %>
At controller:
directory = "public/job_files"
Find.find( directory ) do |fpath|
if FileTest.file?( fpath )
fpath.clone(params[:file])
end
end
But file not upload the parameter do get submit of form.
Thanks
In controller:
name = params['file'].original_filename
uploaded_io = params['file']
File.open(Rails.root.join('public', 'job_files', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end

Rails hit new method on save of simpleform

So i have this method
def create
#newevent = Event.new(create_params)
#newevent.save!
flash[:success] = "Event Created"
redirect_to "/events"
end
And this form
<% provide(:title, "Edit user") %>
<h1>Editing event:
<%= #newevent.id %></h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= simple_form_for #newevent do |f| %>
<div class="form-group">
<%= f.label :eventname %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventname, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.input :event_type, :collection => ['Concert','Festival','Sports','Theatre'] %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventdesc %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventdesc, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventshortdesc %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventshortdesc, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :pagetitle %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :pagetitle, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :metatag %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :metatag, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventvenuename %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventvenuename, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.input :time, type: "time", :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.input :date, type: "date", :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventimage %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventimage, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.check_box :eventready %>
<%= f.label :eventready, "Is event ready for SEO?" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.check_box :eventcomplete %>
<%= f.label :eventcomplete, "Is event ready for Public?" %>
</div>
</div>
</div>
<%= f.submit "Save changes", class: "btn btn-info" %>
<%= link_to "Delete", event_path(#newevent), :method => :delete, class: "btn btn-danger" %>
<% end %>
</div>
</div>
I'm currently populating this form with the edit method here
def edit
#newevent = Master.find(params[:id])
end
How can i go about making this pull in information from the Master table to auto populate the table but then save to the Event table?
Sam
What about a simple update method?
def update
#newevent = Event.find(params[:id])
if #newevent.update_attributes(params[:newevent])
redirect_to #user
else
render action: "edit"
end
end

Why "error_message" don't show error ActiveRecord validate?

Im worked on a project that create events.But I click on a "create event" button with empty fields partial "_error_messages" don't render list with a errors.The page the page is loaded again.Validates seems to be working, in rails console I tried to create and bash show me an error "can't be blank".
This is my _event_form.html.erb
<%= form_for event, html: { class: "event-form" } do |f| %>
<%= render 'shared/error_messages', event: event %>
<% unless current_user %>
<div class='row'>
<div class='col-md-4'>
<div class="form-group col-sm-12">
<%= label :email, "Введите Ваш email:" %>
<%= text_field_tag :email, "",class: "form-control" %>
<small>Он нужен для того, что бы Вы могли позже отредактировать добавленное Вами событие.</small>
</div>
</div>
</div>
<% end %>
<div class="row">
<div class="col-md-8">
<div class="form-group col-sm-12">
<%= f.label "Название" %>
<%= f.text_field :name, class: "form-control" %>
</div>
<div class="form-group col-sm-4">
<%= f.label "Изображение" %>
<%= image_tag event.image, class: "img-responsive" if event.image.present? %>
<%= f.file_field :image %>
</div>
<div class="form-group col-sm-4">
<%= f.label "Город" %><br />
<%= select_tag :city_id, options_from_collection_for_select(City.all, :id, :name), name: "event[city_id]", placeholder: "Город" %>
<%#= f.file_field :image %>
</div>
<div class="form-group col-sm-12">
<%= f.label "Описание" %>
<%= f.text_area :description, class: "form-control", rows: 10 %>
</div>
<div class="form-group col-sm-12">
<%= f.label "Адрес" %>
<%= f.text_field :address, class: "form-control", id: :address %>
<div id='map'></div>
</div>
</div>
<div class="col-md-4">
<div class="form-group col-sm-6">
<%= f.label "Цена от" %>
<input name="event[price][min_price]" value="<%= event.price.try(:min_price) %>" class="form-control" type="number" min="0" />
<%= f.label "Цена до" %>
<input name="event[price][max_price]" value="<%= event.price.try(:max_price) %>" class="form-control" type="number" />
<%= f.label "Тип цены" %>
<br />
<%= select_tag :price_types, options_from_collection_for_select(PriceType.all, :id, :name), name: "event[price][price_type_id]", placeholder: "Выберите тип цены" %>
</div>
<div class="form-group col-sm-6">
<%= f.label "Время проведения" %>
<%= f.text_field :time, class: "form-control", type: :time %>
</div>
<div class="form-group col-sm-6">
<%= f.label "Тип отдыха" %>
<br />
<%= select_tag :types, options_from_collection_for_select(Type.all, :id, :name, selected: event.types.pluck(:id)), name: "event[types_ids][]", placeholder: "Тип отдыха" %>
</div>
<div class="form-group col-sm-12">
<%= f.label "Дата проведения" %>
<div id="mdp"></div>
<input type='hidden' name="event[days]" class="form-control" id="mdp_alt" />
</div>
</div>
</div>
<div class="form-group text-right">
<%= f.submit class: "btn btn-primary" %>
</div>
<% end %>
<script>
$(document).ready(function(){
var dates = <%= event.days.pluck(:date).map{ |d| d.to_s.to_datetime.to_i * 1000 } %>;
if(dates.length){
var settings = {
altField: '#mdp_alt',
dateFormat: "yy-mm-dd",
addDates: dates
}
}else{
var settings = {
altField: '#mdp_alt',
dateFormat: "yy-mm-dd"
}
}
$('#mdp').multiDatesPicker(settings);
})
</script>
this is my _error_messages.erb
<% if event.errors.any? %>
<div id="errorExplanation">
<h2> В форме обнаружено <%= pluralize(event.errors.count, "ошибка", "ошибки") %>:</h2>
<ul>
<% event.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
what's wrong?

Resources