Setting default value for Rails select helper block - ruby-on-rails

How can I set default value in Rails select helper block?
<div class="field">
<label>Gender</label>
<%= f.select :gender, [], { prompt: 'Select gender', selected: 'Female' }, { :class => 'ui selection dropdown' } do %>
<% Subject.genders.keys.each do |c| %>
<%= content_tag(:option, value: c, class: 'item') do %>
<%= content_tag(:i, '', class: "#{c.downcase} icon") %>
<%= content_tag(:span, c) %>
<% end %>
<% end %>
<% end %>
</div>
I tried setting it with :selected option but it doesn't work.

I don't think if selected exist for f.select.
You can use options_for_select(values, value_selected)
Suggestion:
You can create a file named app/helpers/select_helper.rb. In this file, you create a function like this:
def subject_genders_values
Subject.genders.each do |c|
[c.value, c.value]
end
end
your function subject_genders_values can be re-used. And every time if you want a select box, you can create your function in this file.
Notice: add
include SelectHelper
in application_helper.rb
And your views:
<%= f.select :gender,options_for_select(subject_genders_values, 'Female') %>
The option Female will be selected if it's a part of the list.

Related

can't write unknown attribute `example` typed_store - Rails

I have this models where I wanna update my typestored columns using update_columns active record
I have searched numerous answers in stack, doesn't seems to have lot of resources regarding typestored.
show.html.erb
<%= form_tag print_booking_path(#booking), method: 'post' do %>
<%= label_tag :name %>
<%= text_field_tag :name, '', class: 'form-control' %>
<%= label_tag :age %>
<%= text_field_tag :age, '', class: 'form-control' %>
<%= submit_tag "Print", class: "btn btn-default" %>
<%= link_to 'Cancel', '#', class: 'btn btn-default', data: { dismiss: 'modal' } %>
<% end %>
bookings_controller
def print
#booking = Booking.find(params[:id])
if #booking.print_model(current_user, params[:name], params[:age])
render :print
else
render :print
end
end
booking model
def print_model(user, name_test, age_test)
self.update_columns(name: name_test, age: age_test)
end
typestore under booking model
typed_store :profile, coder: PostgresCoder do |i|
i.string :name, default: ""
i.integer :age, default: 0
end
the error appeared to be like this
can't write unknown attribute name
it's same like if I wanna to update like this self.increment!(:age)
I made a few tests here, and I don't know if it makes sense, but in case of updating stores, all the typestored columns are inside just one real column in the database (that are a normally in hash or Json).
So the straight foward way to do it is to wrap in brackets.
Try changing:
self.update_columns( name: name_test, age: age_test )
To:
self.update_columns( profile: { name: name_test, age: age_test} )

Display checkbox instead of drop down select

I have the following form:
<%= form_for #user do |f| %>
<div class="form-group">
<%= f.label :extra_act %>
<%= f.select(:extra_act, [['Act 1', 1],['Act 2', 2], ['Act 3', 3]], class: 'form-control', required: true) %></br>
</div>
<%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>
Is there a way to offer checkboxes instead of the drop down select menu here? I have found checkboxes on the ruby website, but I only want users to have the option of selecting one checkbox.
This will work with rails 4+
You want the user to select only one value so instead of check_box you need radio button. Here is how you can do it(syntax):
collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
Something like this with your code:
f.collection_radio_buttons(:extra_activity_id, ExtraActivity.all, :id, :title, html_options: { class: 'form-control' }
For rails 3 you will need to loop on the extra activities:
<% ExtraActivity.all.each do |ea| %>
<%= f.radio_button :extra_activity_id, ea.id %>
<% end %>
As you don't have this is database and you are using an array then do it like this, it may work:
f.collection_radio_buttons(:extra_activity_id, [['Act 1', 1],['Act 2', 2], ['Act 3', 3]], :last, :first, html_options: { class: 'form-control' }
You can either use a single select list (meaning multiselect attribute should be off) or a radio group.
Whichever suits your needs.

Rails 4 dropdown menu pulling from database

I am trying to implement a dropdown menu to display all the names I have in my database. I tried unsuccessfully the following code:
<%= form_for #airline, remote: true do |f| %>
<%= f.select :name, [#airlines.names] %>
<%= f.submit %>
<% end %>
Controller:
def index
#airlines = Airline.all
#airline = Airline.new
end
I assume the solution is quite straight forward but I couldn't find it.
This should do
<%= f.select(:name, #airlines.collect { |airline| [airline.name,airline.id] }, {:include_blank => 'Choose 1'},:class=>"class_name") %>

Ruby On Rails - validate nested params in controller (must not be nil)

These are my params:
{"utf8"=>"✓", "authenticity_token"=>"0RYiIDDgmOk0gCDRkAgHvv+UIgp/BuU33CLThJXqOTE=",
"order"=>
{"operation_in_orders_attributes"=>
{"0"=>{"service_operation_id"=>"5"},
"1"=>{"service_operation_id"=>""},
"2"=>{"service_operation_id"=>"4"},
"3"=>{"service_operation_id"=>""},
"4"=>{"service_operation_id"=>""}},
"kontakt"=>"comment", "Car_id"=>"50"},
"commit"=>"Dodaj",
"car_id"=>"dw815gn"}
Order has many operation_in_orders
Order has many service_operations through OperationInOrder
OperationInOrder belongs to Order
OperationInOrder belongs to ServiceOperation
ServiceOperation has many operation_in_orders
ServiceOperation has many orders through OperationInOrder
My form:
<%= form_for #order, url: new_car_order_path(#car, #order), html: {class: "add_order"} do |r| %>
<%= r.label "Service", class: :add_order_label %>
<% 5.times do %>
<%= r.fields_for :operation_in_orders do |v| %>
<%= v.collection_select(:service_operation_id, ServiceOperation.all, :id, :nazwa,include_blank: true) %>
<!-- <%= v.text_field :order_id, value: #order.id, :style => "display:none" %> -->
<% end %>
<% end %>
<%= r.label "Kontakt", class: :add_order_label %>
<%= r.text_field :kontakt %>
<%= r.text_field :Car_id, value: #car.id, :style => "display:none" %>
<%= r.label " " %>
<%= r.submit "Add", class: "sub" %>
<%= link_to "Send",ordered_path(car_id: #car.id) , class: 'sub'%>
<% end %>
I have a form where I can choose five ServiceOperations at most to an order and save.
When I save, 5 new OperationInService objects/rows are made.
Is there a possibility to not create those join tables if corresponding field on form is blank?
For example:
I fill only 2 from 5 fields. I save only these two, not 5. Now I save nil values...
I have tried to validate in OperationInService model, but there was an error (rails do not recognize format in controller).
Any ideas?
Update the accepts_nested_form_for method call in Order model as below:
class Order < ActiveRecord::Base
has_many :operation_in_orders
accepts_nested_attributes_for :operation_in_orders, reject_if: proc { |attributes| attributes['service_operation_id'].blank? }
## ..
end
This way record for operation_in_orders would not be created if service_operation_id is blank.

Rails check_box_tag within form_for

Is it possible to pass the value of checked check_box_tags within a form_for in Rails inside a hash?
Here is a very generic, basic version of the form:
<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
<p>Field_a: <%= f.text_field(:field_a) %></p>
<p>Field_b: <%= f.text_field(:field_b) %></p>
<p>Field_c: <%= f.text_field(:field_c) %></p>
<p>Check boxes:</p>
<% check_box_choices_object_array.each do |s| %>
<%= check_box_tag(s.name, 1, false) %>
<%= .name %><br />
<% end %>
<%= submit_tag("Create") %>
<% end %>
Outputs roughly:
Field_a ___________________
Field_b ___________________
Field_c ___________________
Check boxes:
[] box_a
[] box_b
[] box_c
[] box_d
[] box_e
[] box_f
[] box_g
My problem is that since the available check boxes aren't actual fields in the object's table in the database (i.e. I'm not using check_box(:field) in the form), each checked check box gets passed as an individual parameter (i.e. "box_a" => "1", "box_b" => "1", "box_e" => "1"). I would like them to be passed as such:
:checked_boxes => {"box_a" => "1", "box_b" => "1", "box_e" => "1"}
This way, I can access them easily with params[:checked_boxes].
How do I do this, or, better yet, is there a better solution (I'm new to rails)?
I think you'd get the results you want if you wrap the checkboxes iterator in a fields_for :checked_boxes tag - or at least get you close to the results you want.
<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
<p>Field_a: <%= f.text_field(:field_a) %></p>
<p>Field_b: <%= f.text_field(:field_b) %></p>
<p>Field_c: <%= f.text_field(:field_c) %></p>
<p>Check boxes:</p>
<%= f.fields_for :checked_boxes do |cb| %>
<% check_box_choices_object_array.each do |s| %>
<%= cb.check_box(s.name, 1, false) %>
<%= .name %><br />
<% end %>
<% end %>
<%= submit_tag("Create") %>
<% end %>
you can deal with no database attributes and models using attr_accessor
class Thing < ActiveRecord::Base
attr_accessible :name
attr_accessor :box_a, :box_b, :box_c
end
This way you can call these attributes in your form.

Resources