how to check the collection_radio_buttons selected for if condition? Rails - ruby

I have this form
<div class="form-group">
<%= f.label :status %>
<%= f.collection_radio_buttons(:status, options_for_status, :id, :description) do |b| %>
<div class="radio">
<%= b.label { b.radio_button + b.value} %>
</div>
<% end %>
</div>
if ??
#<% f.hidden_field :data_fim, :value => Date.today %>
When the user selects a specific radiobuton, he must execute hiden_field.
STATUS = {:Aguardando => 1, :'Em atendimento' => 2, :Finalizado => 3}
These are the options present for the user, I want to set set date_fim when the user select the radio
:Finalizado => 3
Would JS be my only option? Someone to help a noob in ruby?

This should work, assuming that jQuery is included in your assets.
<script type="text/javascript">
$(document).ready(function(){
$('.radio').click(function(){
$('#data_fim').val($(this).val());
});
});
</script>

Related

Rails sending multiple params through dropdown box

I have two dropdown boxes. One is for campaign size(small, medium, large) and the other one is for the theme selection.
I want to be able to send params dynamically through onchange event handler
current code looks like this
<div class="col-lg-12 col-padding-helper">
<%= form_tag product_builder_path, method: :get do %>
<div class="col-lg-5 col-padding-helper">
<%= label_tag 'Campaign Size' %></br>
<%= select_tag 'type', options_for_select(['Small (4 Products)', 'Medium (7 Products)', 'Large (10 Products)' ]), multiple: false, :include_blank => true, class: "form-control", data: { remote: true }, onchange: "this.form.submit();" %>
</div>
<% end %>
<%= form_tag(product_builder_path, method: :get, remote: true) do %>
<div class="col-lg-7 col-padding-helper">
<%= label_tag 'Theme' %></br>
<%= select_tag 'theme', options_for_select(['Default BWX Theme', 'Black Friday Theme']), multiple: false, :include_blank => true, class: "form-control", onchange: "this.form.submit();" %>
</div>
<% end %>
</div>
The workflow that I am thinking in my head is that once user selects the campaign size it will submit a form through ajax and have something like this as a url. which then I can display display right type of html template on the webpage.
/product_builder?type=small
and after when they select the theme is it possible to do something like this? and this will change the theme of the type that I have chosen above
/product_builder?type=small&theme=black
so basically it's adding params to current URL
I don't even know if this is possible, any help or guidance would be awesome
Thank you

How to get parameters value in model from views form in rails?

Here is my new.html.erb
<%= form_for :simulation, url: simulations_path do |f| %>
<div class="form-group">
<%= f.label :Name %>
<div class="row">
<div class="col-sm-2">
<%= f.text_field :name, class: 'form-control' %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :'Rendering Option' %>
<div class="Dropdown">
<div class="col-sm-4">
<%= select_tag(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<%= f.submit 'Submit', class: 'btn btn-primary' %>
</div>
simulations_controller.rb
class SimulationsController < ApplicationController
def index
#simulations = Simulation.all
end
def new
end
def create
#simulation = Simulation.new(simulation_params)
#simulation.save
redirect_to #simulation
end
def show
#simulation = Simulation.find(params[:id])
end
end
Simulation.rb (Model class)
class Simulation < ActiveRecord::Base
belongs_to :user
end
Schema.rb
create_table "simulations", force: :cascade do |t|
t.string "name"
t.boolean "is_random"
end
I am not able to set the :is_random value in database while rest is fine. What I am doing wrong here? I checked the value in sqlite database and there was null entry in is_random column.
You need to permit attributes while doing mass assignment. You could write it as :
<%= f.select(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
or
<%= select_tag("simulations[:is_random]", options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
With your syntax, the value is inside the params hash as {..., is_random: true,..}, that's why inside the strong parameter filtering method you are not getting it. If you use now the suggested solutions, you will get it the value inside the params hash like {..., simulations: { is_random: true,..}, ...}.
You can inspect all these from the the development.log file, while making the request.
You need to use form object select method like bellow:
<%= f.select(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
Using f.select (suggested above) should fix your problem. If you look at the generated html, you will see this field with a name of "is_random". It should be "simulations[is_random]". When you pull the form field values from the params object like this params[:simulations] all form fields with names in the form of "simulations[name]" will be included. Using the form builder object names the form fields correctly.
Hope this helps!
You can also use <%= debug params %> to inspect what's in params, it's very helpful.

Partner() expected, got String()

I have a course model and there is a many to many relationship with category, i am using a multi select on my form to get an array of objects, A course also can have a partner and the user can select this from a single select, but when i want to save to the database I call the params then I get a string instead of an object. not to sure how I can solve this
<%= form_for #course do |f| %>
<section class="new_course">
<div class="row collapse">
<div class="medium-5 small-centered column">
<%= f.label :course_title, :class=>"custom-prefix-class" %>
<%= f.text_field :title, :autofocus => true, :class=>"custom-input-class" %>
</div>
</div>
<div class="row collapse">
<div class="medium-5 small-centered column">
<%= f.label :start_date, :class=>"custom-prefix-class" %>
<%= f.text_field :start_date, :class=>"custom-input-class" %>
</div>
</div>
<div class="row">
<div class="medium-5 column with_chosen">
<%= f.collection_select :categories,
Category.all ,:id,:name,
{ include_blank: true},
{ class: 'chosen-select', :multiple=>true, :data => { :placeholder => ' ' }}
%>
</div>
</div>
<div class="row">
<div class="medium-5 column">
<%= f.collection_select :partner,
Partner.all.collect, :id,:name ,
{ include_blank: true },
{ class: 'chosen-select', :multiple=>false, :data => { :placeholder => ' Brand Partner' }}
%>
</div>
</div>
In my controller
def create
#course = Course.new(course_params)
end
if #course.save
render :action=>'new'
end
end
private
def course_params
params.require(:course).permit(:title, :start_date,:duration,:partner,:categories => [])
end
//rails server output
Started POST "/courses" for 127.0.0.1 at 2014-02-07 16:45:28 +0200
Processing by CoursesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"sKhAF2X6VOXTxZC9Pt51RFQfZSKdzXVWji6x4uwg+rI=", "course"=>{"title"=>"Marketing ", "start_date"=>"14-02-2014", "categories"=>["", "1", "2"], "partner"=>"1", "duration"=>"2-weeks"}, "commit"=>"Add new course"}
Completed 500 Internal Server Error in 3ms
ActiveRecord::AssociationTypeMismatch (Partner(#70274068591140) expected, got String(#70274066607160)):
app/controllers/courses_controller.rb:24:in `create'
try this out:-
it seems as that partner is a model and course has_one partner, so you
have to assign partner class object instead of id as string
actually as you can see in in question above value of
params[:course][:partner]
=> "1"
is a string now if you try to do something like #course.partner
= '1' it will raise an error like above, as on left hand side we have parter association and right and side a string.
just do this
def course_params
params.require(:course).permit(:title, :start_date,:duration,:partner,:categories => [])
if params[:course][:partner].present?
params[:course][:partner] = Partner.find params[:course][:partner]
end
end

Get value of a hidden field tag Ruby on Rails

I am lost, I do not know what I'm doing wrong! I have 4 radio buttons and a hidden field (value = "1"). When you click on the second radiobutton, the value of the hidden field changes to 2 and so on. This works fine with a js function.
Different divs will be showed when a different radiobutton is selected. Now, when I'm trying to get the value of the hidden field in my controller it always returns nil.
Here's the code:
view:
(radiobuttons, hiddenfield and one div)
<div>
<%= form_tag patients_path do %>
<%= radio_button_tag 'searchRBN', 'patient', true, :onchange => "checkRadioButton()" %>
<%= label_tag :byPatient_patient, "Patient" %>
<%= radio_button_tag 'searchRBN', 'staff', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byStaff_staff, "Staff" %>
<%= radio_button_tag 'searchRBN', 'ocmw', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byOcmw_ocmw, "OCMW" %>
<%= radio_button_tag 'searchRBN', 'mutuality', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byMutuality_mutuality, "Mutuality" %>
<%= hidden_field_tag :hidden_one, "1" %>
<% end %>
</div>
<div id="searchByPatient">
<%= form_tag patients_path, :method => 'get' do %>
<p>
<%= text_field_tag :search1, params[:search1] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
</div>
controller:
def index
#staff_all = Staff.all
#ocmw_all = Ocmw.all
#mutuality_all = Mutuality.all
debugger
if params[:hidden_one] == '1'
#patients = Patient.searchByName(params[:search1])
elsif params[:hidden_one] == '2'
#patients = Patient.searchByStaff(params[:search2])
else
#patients = Patient.all
end
end
It's because you have two forms. When you submit the second form it won't send the fields of the first form. If you put everything in one form it will work as expected.
Use only single form:
Also as a workaround use two submit tag in a single form:
differentiate both the action with params[:action]
For Example:
<%= form_for :attachment_metadata, :url=>{:action=>'delete_files'}, :html=>{:onsubmit=> "return confirm('Are you sure, you want to delete selected files?');",:multipart => true} do |f| %>
<table>
..........Some stuff here..........
</table>
<%= submit_tag 'Reprocess', :class =>'button' %>
<%= submit_tag 'Remove', :class =>'button' %>
<% end %>
params[:commit] can differentiate the actions of two submit tags.
#action = params[:commit]
it gives #action value as "Reprocess" if your click the Reprocess button and gives "Remove" value if you click the Remove button,
Then you will get your values.

TinyMCE for rails 3.1

in show page, i will convert string into hash,
form.html.erb
<%= f.text_area :content, :rows => 20, :cols => 120 %>
<script type="text/javascript">
$(function() {
$('textarea').tinymce({
theme: 'advanced'
});
});
</script>
show.html.erb
<p>
<%= #page.content %>
</p>
<p>
<%= link_to "Edit", editcontent_path(#page), :class => "abutton" %> |
<%= link_to "Destroy", destroycontent_path(#page), :confirm => 'Are you sure?', :method => :delete %> |
<%= link_to "View All", admins_view_content_path %>
</p>
but my page following, code not convert
I have not used tinymce , but as per documentation what I understand is
If you want to add content to editor pass that to the text area
<%= text_area_tag :editor, #page.content , :class => "tinymce", :rows => 40, :cols => 120 %>
# you can pass configuration option to tinymce here
<%= tinymce %>
In Show page
<p>
<%= #page.content.html_safe %> #Apply html_safe function to interpret string as html
</p>
This works for me.
Optionally raw(#page.content) also works

Resources