How to save the radio button selection in database using rails - ruby-on-rails

This is my controller:
class ReportNeedsController < ApplicationController
def index
#report_needs = nil
end
def new
#report_need = ReportNeed.new
end
def create
#report_need = ReportNeed.new(params[:report_need])
#report_need.save
redirect_to #report_need
end
end
This is my new.haml file:
Why do you want to report?
%form
%input{:name => "option", :type => "radio", :value => "spam"}
spam
%br/
enter code here
%input{:name => "option", :type => "radio", :value => "product_corrupted"}
product_corrupted
%br/
%input{:name => "option", :type => "radio", :value => "product_spoiled"}
product_spoiled

Make changes in view like :
%input{:type => "radio", :name => "report_need[product_type]", :id => "report_need[product_type]-1", :value => "salesforce", :checked => true}
%br/
%input{:type => "radio", :name => "report_need[product_type]", :id => "report_need[product_type]-2", :value => "salesforce", }
In controller, If product_type is field of table report_needs then no need to change in your action . else its change and store it like :
def create
report_need = ReportNeed.new(params[:report_need])
report_need.radio_field_name = params[:report_need][product_type]
report_need.save
redirect_to report_need
end

Related

Rails 4 Client Side Validations on Simple Form not working inline?

Hi I need some more help.
I'm following this tutorial on using client_side_validation: Railcasts: Client Side Validations. It seems straight forwardly easy to use however I can't find how to make it my inline errors show.
Reports Model
Class Report < ActiveRecords::Base
attr_accessor :producer_selected, producer_id
belongs_to :producer
validates :producer_selected, presence => true
....
Reports Controller
Class ReportsController < ApplicationController
def generate_clients
#report = Report.new(report_params)
#report.queue_status = "Completed"
#report.created_by = current_user.id
respond_to do |format|
if #report.save
#producer = Producer.find(params[:report][:producer_id])
....
if #report.report_type == "Clients per Producer"
requests = Request.from_date_range(params[:report][:from_due_date], params[:report][:to_due_date])
#records = requests.records(params[:report][:producer_id])
end
format.html {
outstrio = StringIO.new
#report.update_attribute(:date_start, DateTime.now)
p = render_to_string handlers: [:axlsx], formats: [:xlsx], template: "reports/create_clients"
outstrio.write(p)
#report.update_attribute(:date_end, DateTime.now)
send_data outstrio.string, filename: "#{DateTime.now.to_date} #{#report.report_name}.xlsx"
}
format.json { render :show, status: :created, location: #report }
else
puts #report.errors.full_messages
format.html { redirect_to :back, alert: 'Both dates must be filled up.' }
format.json { render json: #report.errors, status: :unprocessable_entity }
end
end
end
_clients_form.html.haml
= simple_form_for #report, :validate => true, url:generate_clients_reports_path do |f|
= f.error_notification
.form-inputs
.form-group.col-md-12
=f.label :from_due_date, :label => "From:", class: "col-md-2 text-right", :style => "margin-top:6px;"
=f.date_field :from_due_date, :as => :date, class: "range-control col-md-2"
=f.label :to_due_date, :label => "To:", class: "col-md-2 text-right", :style => "margin-top:6px;"
=f.date_field :to_due_date, :as => :date, class: "range-control col-md-2"
.form-group.col-md-12
=f.input :report_type, :as => :select, :collection => #report_types, :wrapper => :field_multi8, :label_html => {:class => "col-md-2 text-right"}, :input_html => {:class => "form-control"}, :label => "Report Type:", :include_hidden => false, :include_blank => false
.form-group.col-md-12
= f.input :producer_selected, :url => autocomplete_producer_search_string_requests_path, :required => :true, :as => :autocomplete, :wrapper => :field_multi8, :label_html => { :class => "col-md-2 text-right" }, :input_html => { :class => "form-control" }, :id_element => "#report_producer_id", :label => "Producer/Client :", :placeholder => "Find Producer", :update_elements => {}, :autofocus => true
= f.input_field :producer_id, :as => :hidden
client_side_validations.rb
require 'client_side_validations/simple_form' if defined?(::SimpleForm)
require 'client_side_validations/formtastic' if defined?(::Formtastic)
<label for="#{instance.send(:tag_id)}" class="message"></label>
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
unless html_tag =~ /^<label/
%{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
else
%{<div class="field_with_errors">#{html_tag}</div>}.html_safe
end
end
Gem is installed already in gemfile
Rails 4.2.3
I'm doing all the basic things, but all the basic validations are also not working. After going out-of-focus from the field, no inline validation occurs.
What could be the problem? Help!
EDIT: Also tried this solution but it says that repository is not found.

Rails 3: Text_field_tag default value if params[:something].blank?

How would one do something like:
= f.input_field :age,
:collection => 18..60,
:id => 'age',
:selected => params[:age].blank? or "20"
Above doesen't work. I want to be able to set a default value if there is no param available for that attribute.
Any smart way to do this thx!
EDIT 1:
Full form:
= simple_form_for :people, :url => request.fullpath, :method => :get, :html => { :class => 'form-search' } do |f|
#container_search_small.form-search
= f.input_field :age,
:collection => 18..60,
:id => 'age',
:selected => params[:people][:age_from] || "20"
= f.submit "Go »"
You're using helpers that are taking their values from the object you're building the form on.
So in your controller, you should preset the values on the object.
def some_action
#people = People.new
#people.age = params[:age] || 20
end
Then in the form, remove the :selected option and it should be fine. Make sure you build the form for #people :
= simple_form_for #people, :url => request.fullpath, :method => :get, :html => { :class => 'form-search' } do |f|
#container_search_small.form-search
= f.input_field :age,
:collection => 18..60,
:id => 'age'
= f.submit "Go »"

Rails 2 and ajax - few select lists

I can't figure what i do wrong. I have few select lists:
Regions
Towns
Organizations
How it should works:
User selects region.
List of towns loads.
User selects town.
List of organizations loads.
User chooses organization.
I use ajax for that and i realized only auto-loading for list of towns and i can't do same thing for organization. Second select list DOESN'T POST at all!
Here is my code:
View
%div
%br/
= select 'ajax', :region_id, [['Choose your region...', -1]] + Region.all.map{|region| [region.name, region.id]}.sort
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= observe_field :ajax_region_id, :url => { :controller => :organizations, :action => :list_towns, :preselect => (defined?(preselect) && !preselect.nil?) }, :with => 'region_id', :update => 'select_organization_idd', :loading => '$("ajax-progress").show();', :complete => 'if (Ajax.activeRequestCount == 1) $("ajax-progress").hide();'
%br/
= select 'ajax2', :o_id, [], {}, {:id => 'select_organization_idd', :style => 'width: 60em;'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= observe_field :ajax_region2_id, :url => { :controller => :organizations, :action => :list_region, :preselect => (defined?(preselect) && !preselect.nil?) }, :with => 'o_id', :update => 'select_organization_idd2', :loading => '$("ajax-progress").show();', :complete => 'if (Ajax.activeRequestCount == 1) $("ajax-progress").hide();'
= f.select :organization_id, [], {}, {:id => 'select_organization_idd2', :style => 'width: 60em;'}
Controller
def list_region
render :text => ActionController::Base.helpers.options_for_select((params[:preselect] ? [['Choose organization', -1]] : []) + Organization.map{|org| [ActionController::Base.helpers.truncate(org.name, :length => 155), org.id]})
end
def list_towns
region = Region.find(params[:region_id])
towns = Kladr.find(:all, :conditions => ['code LIKE ?', "#{region.code}%"])
render :text => ActionController::Base.helpers.options_for_select([['Choose town', -1]] + towns.map{ |t| ["#{t.socr}. #{t.name}", t.id] })
end
What do i do wrong? Also i use Rails 2, that why observe_field is not deprecated.
Do you use rails 3? The method observe_field is deprecated.
With rails 3 you must do something like this :
view
%div
%br/
= select 'ajax', :region_id, [['Choose your region...', -1]] + Region.all.map{|region| [region.name, region.id]}.sort, {}, {:id => 'ajax1'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
%br/
= select 'ajax2', :o_id, [], {}, {:id => 'select_organization_idd', :style => 'width: 60em;'}, {}, {:id => 'ajax2'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= f.select :organization_id, [], {}, {:id => 'select_organization_idd2', :style => 'width: 60em;'}
javascript.js.coffee
$('#ajax1').change = () ->
$.post(
url: '/organizations/list_towns'
data: {value: $('#ajax1').val()}
success: () ->
if (Ajax.activeRequestCount == 1)
$("ajax-progress").hide()
)
$('#ajax2').change = () ->
$.post(
url: '/organizations/list_regions'
data: {value: $('#ajax2').val()}
success: () ->
if (Ajax.activeRequestCount == 1)
$("ajax-progress").hide()
)
The implementation is probably wrong and could be refactored. I didn't test it. But you've got the idea.

My form fields are being deleted on submit

And as a result its not passing validation.
This is my embedded form :
- form_for [#organization, #referral] do |f|
= f.error_messages
= render :partial => 'referral_fields', :locals => { :f => f }
= f.submit "Submit", :class => "button"
#_referral_fields.html.haml
.grid_7
.grid_1{:style => "width: 64px;"}
= f.label :org_name, "Business", :class => "right"
.grid_4
= f.text_field_tag :org_name
.grid_7
.grid_1{:style => "width: 64px;"}
= f.label :name, '', :class => "right"
.grid_4
= f.text_field_tag :name
.grid_7
.grid_1{:style => "width: 64px;"}
= f.label :email, '', :class => "right"
.grid_2.omega{:style => "width: 114px;"}
= f.text_field_tag :email, '', :style => "width: 125px;"
.grid_1.alpha
= f.label :town, '', :class => "right"
.grid_2
= f.text_field_tag :town, '', :style => "width: 100px;"
And when I click submit, SQL definately reads the data I inputted :
Processing ReferralsController#create (for ::1 at 2010-10-18 09:39:07) [POST]
Parameters: {"name"=>"asdfasd", "commit"=>"Submit", "action"=>"create", "authenticity_token"=>"/1bwOqHjojde3p0Py08mCrko8xULE4R+eXUvT6qf1cE=", "controller"=>"referrals", "org_name"=>"asdfasdf", "organization_id"=>"1", "town"=>"asdfasd", "email"=>"asdfasd"}
Not sure what I'm missing. Here is controllers and models :
#referral.rb
belongs_to :organization, :touch => true
validates_presence_of :org_name, :name, :email, :town
#referrals_controller.rb
def new
#referral = Referral.new
respond_to do |format|
format.html { render :layout => 'manage' }
end
end
def create
#referral = Referral.new(params[:referral])
if #referral.valid? && #organization.referrals << #referral
flash[:notice] = "Referrals saved."
redirect_to new_organization_referrals_path(#organization)
else
render :action => :new, :layout => 'manage'
end
end
From looking at the parameters, it doesn't look like you have your form fields setup properly?
You are using the params[:referral] hash to build the referral, but I don't see a :referral hash in your parameter list....
Your form fields should look like this:
<input name="referral[name]"/>
<input name="referral[town]"/>
<input name="referral[org_name]"/>
etc...
And then in your parameter list you should be something like { :referral => {:name => "foo", "org_name" => "bar", town => "Boise" } }

create_or_update method in rails

if ClassName.exists?(["id = ?", self.id])
object = ClassName.find_by_name(self.name)
object.update_attributes!( :street_address => self.street_address,
:city_name => self.city_name,
:name => self.org_unit_name,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code)
else
ClassName.create! :street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:name => self.org_unit_name,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code
end
I have code like this. I would like to improve it so that it uses a method, something like create_or_update.
ClassName.create_or_update_by_name(:name => self.name,
:street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:name => self.org_unit_name,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code)
If the name exists in the database then it should update that object otherwise it should create a new object.
Is there is any method that exists that I can do this with?
my_class = ClassName.find_or_initialize_by_name(name)
my_class.update_attributes(
:street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code
)
As of Rails 6, update_attributes! and update_attributes is deprecated for update! and update, respectively:
my_class.update(
:street_address => self.street_address,
:city_name => self.city_name,
:federalid => self.federalid,
:state_prov_id => self.state_prov_id,
:zip_code => self.zip_code
)
The checked answer above works well for Rails 3. That said the find_or_initialize_by_attribute methods were deprecated in Rails 4. This is the new way. See Rails4 Deprecation warning for find_or_initialize_by method
person = Person.find_or_initialize(name: 'name')
person.update_attributes(other_attrs)
person = Person.find_by_name(name) || Person.new(:name => name)
person.update_attributes!(:street_address => street_address, :city_name => city_name) #etc etc

Resources