<%= f.check_box:TYPE %> AB <br><br>
I have used the above mentioned in my code and when i click submit it takes 1 if checked and 0 if not checkedand it is stored in db. How can i store a string like AB if checked and nil if not checked and i want to store that string in db instead of 0 and 1?
This is the definition of this helper method:
check_box (object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
So I supose you need something like:
<%= check_box :type, {}, "AB", "nil" %> AB <br><br>
But in your rails application you get string 'AB' and string 'nil', that how it works.
Rails 3.2 # http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
ex.
<%= f.check_box( :type, {}, "yes", "no") %>
Related
I have a controller called "Questions" with two actions, "practice" and "grade" both are get routes, the practice view renders a small sample of of Questions and uses forms to get user answers using submit to get the "grade path"
to grade it, I need the record objects to be passed as an array, but when passed using the hidden field I get the reference numbers as strings and not the actual object. how do i get the object so I can call question_object.answer
controllers/questions.rb
def practice
#questions = Questions.find(params[:id])
#sample_array = #questions.multiple_choices.sample(params[:number_of_multiple_choices].to_i)
#sample_array += #questions.true_falses.sample(params[:number_of_true_falses].to_i)
#user_answers = Array.new(#questions.size, 1)
end
def grade
#questions = Questions.find(params[:id])
#sample_array = params[:sample_array]
#array_answers = # create array based on sample_array's answers
#user_answers = params[:user_answers].split(' ')
#user_answers = #user_answers.map.with_index{|x,y| params[("user_answer#{y.to_s}")] }
end
views/questions/practice.html.erb # don't mind the finite number of forms its just for example.
<%= form_for :grade, :url => grade_path, method: :get do |f| %>
<%= hidden_field_tag(:sample_array, #sample_array) %>
<%= hidden_field_tag(:user_answers, #user_answers) %>
<div class="form-group">
<%= select_tag(("user_answer#{0}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
<%= select_tag(("user_answer#{1}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
<%= select_tag(("user_answer#{2}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
<%= select_tag(("user_answer#{3}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
</div>
<div id="finalscore">
<%= button_to "act_2", class:'btn btn-success' %>
</div>
<% end %>
in grade the parameters i passed are just strings like so. questions: ["#", "#", "#"]
I researched it and hidden_fields will pass query_strings and that's why im only getting strings, but I can't find any examples on how to obtain the array object to use in my grade controller action.
thanks in advance sorry for the long question I don't know how else to ask about this.
Instead of creating the arrays in your practice method, why don’t you create them in your grade method? To do this, you can instead assign #number_of_multiple_choice and #number_of_true_false in your practice method, pass those numbers in the hidden field tag, and determine your arrays in the grade action. I’m actually not sure what you’re trying to do with #user_answers in the practice action - I assume you’re just trying to create one empty answer object, but it does not appear to be used that way in the form.
controllers/questions.rb
def practice
#question = Question.find(params[:id])
#number_of_multiple_choices = params[:number_of_multiple_choices].to_i
#number_of_true_falses = params[:number_of_true_falses].to_i
end
def grade
#question = Question.find(params[:id])
#sample_array = #questions.multiple_choices.sample(params[:number_of_multiple_choices].to_i)
#sample_array += #questions.true_falses.sample(params[:number_of_true_falses].to_i)
#array_answers = # create array based on sample_array's answers
#user_answers = params[:user_answers].split(' ')
#user_answers = #user_answers.map.with_index{|x,y| params[("user_answer#{y.to_s}")] }
end
views/questions/practice.html.erb
<%= form_for :grade, :url => grade_path, method: :get do |f| %>
<%= hidden_field_tag(:number_of_multiple_choice, #number_of_multiple_choice) %>
<%= hidden_field_tag(:number_of_true_falses, #number_of_true_falses) %>
...
<% end %>
Additionally I noticed you’re saying #questions = Questions.find(params[:id]. The .find is meant to return one record but you have a) pluralized your variable indicating you want multiple questions, and b) pluralized your model, which is not standard convention. Either your model should be renamed or that will throw an error if your model is actually not pluralized.
I have the following form setup:
= simple_form_for(#job, url: job_payment_path, html: { id: 'payment-processor-form' }) do |j|
div[class='row']
div[class='col-md-12']
div[class='panel panel-default']
div[class='panel-heading']
h3[class='panel-title']
|Total Cost
div[class='panel-body']
h2[class='job-cost' data-initial = "#{job_base_price}"]
= number_to_currency(job_base_price)
div[class='panel-heading']
h3[class='panel-title']
|Have a coupon?
div[class='panel-body']
div[class='row-inline']
div[class='row-block row-block-one']
= j.simple_fields_for :coupon_attributes, #job.coupon do |c|
= c.input_field :code, maxlength: 50, id: 'coupon-code', class: 'form-control', data: { 'initial' => 0 }, include_blank: false
div[class='row-block']
button[type='button' class='btn btn-primary' id='coupon-verify' ]
|Verify
p[class='help-hint']
= t('simple_form.hints.coupon.code')
div[class='row']
div[class='col-md-12']
= j.button :button, type: 'button', class: 'btn-primary text-uppercase', id: 'purchase-job' do
= job_posting_button_step_label
When this form submits, I am seeing the following attributes:
This is not right.
I would expect the coupon code to be nil, not "".
Am I missing something here?
I see two things:
first:
:include_blank is an option for select fields, it skips the generation of a blank option tag at the beginning. code is an input field. If you want to force an input value, try required: true.
second:
form values are sent to the server as application/x-www-form-urlencoded. Empty imput fields are sent as i.e. job[coupon_attributes][code]=. There is no distinction between an empty string and no value.
The convention in Rails is to interpret all input values as string (and typecast later when assigning values to models). So an empty value is always returned as ''.
I have a form where a user can elect to create more input areas (to provide more information). I have a link the user will click on and then the extra form inputs will be created. I'd like to use the rails form helpers so that I don't have to write the html myself. I've tried inserting the form helpers directly into coffeescript and saving the outputted html to a data tag on the link, but I can't get the coffeescript to execute the ruby code and I'm having escaping issues with the data attribute.
Here's the form:
= simple_form_for([#site, #zone]) do |f|
= f.error_notification
.form-inputs
= f.input :site_id
= label_tag "X"
= text_field_tag 'x_coords[]'
= label_tag "Y"
= text_field_tag 'y_coords[]'
= label_tag "X"
= text_field_tag 'x_coords[]'
= label_tag "Y"
= text_field_tag 'y_coords[]'
= label_tag "X"
= text_field_tag 'x_coords[]'
= label_tag "Y"
= text_field_tag 'y_coords[]'
= link_to "Add Point", "#", id: "add_point", data: { fields: label_tags }
.form-actions
= f.button :submit
When a user clicks the "Add Point" link, I'd like to add another block of:
= label_tag "X"
= text_field_tag 'x_coords[]'
= label_tag "Y"
= text_field_tag 'y_coords[]'
label_tags is in application_helper.rb:
def label_tags
label_tag "Z"
end
The problem is the output for the "Add Point" link is:
Z" id="add_point">Add Point
and the quotation marks are causing the link to come out with the text: "Z" id="add_point">Add Point"
I got the data attribute idea from this screencast
You cannot execute Ruby code from Javascript. When the page is requested all embedded ruby is evaluated and the results are what you get. The issue that I can see from you paste is that your label block is in the right data attribute but it's not escaped.
What you'll need to do is escape the quotes on the generated HTML going into that field and then unescape them via Javascript. You could use html_escape here like: data: { fields: h(label_tags) } (h is an alias for html_escape or you could do this yourself, manually.
def escape(str)
str.gsub(/</, "<").gsub(/>/, ">").gsub(/"/, """)
end
# later in the view for the form
data: { fields: escape(label_tags) }
And then your CoffeeScript would click handler would like:
function unescape(str) {
return str.replace(/((?:<)|(?:>)|(?:"))/g, function($1) {
switch($1) {
case ">":
return ">";
case "<":
return "<";
case """:
return '"';
}
});
}
$("a").on("click", function() {
var html = unescape(this.data("fields"));
$(".the-place-to-put-it").html(html);
});
I do not doubt a better solution exists and as of the posting of this answer I have not tested this to work (in theory it should). Ideally, you should just generate the elements with jQuery in Javascript and not depend on this method for doing this - yes, it's duplicate code duplicated between ruby and Coffee.
Simple solution for me was to replace the double quotes in my generated HTML with single quotes. In code:
= link_to "Add Point", "#", id: "add_point", data: { fields: label_tags.gsub("\"", "'") }
Also, had to use capture and concat in the helper method:
module ApplicationHelper
def label_tags
capture do
concat label_tag "X"
concat text_field_tag 'x_coords[]'
concat label_tag "Y"
concat text_field_tag 'y_coords[]'
end
end
end
I have an array [["Company Name", "Field6"], ["Email", "Field5"]]
And from that array I am creating array of fields with values:
[
[{:label=>"Company Name", :value=>"gfdgfd"}],
[{:label=>"Email", :value=>"gfdgfd#gfd.pl"}]
]
using
fields = [["Company Name", "Field6"], ["Email", "Field5"]]
# first element in array is Label and second is param id
fields_with_values = fields.collect do |field|
[
label: field[0],
value: params[field[1]]
]
end
and then I want to pass that labels and values to erb template(something like):
# template.erb
<% fields_with_values.each do |field| %>
l: <%= field.label %>
v: <%= field.value %>
<% end %>
How will be the best way to collect these fields_with_values ? Maybe I should use Object.new
Convert to a hash instead.
fields = [["Company Name", "Field6"], ["Email", "Field5"]]
fields_with_values = Hash[*fields.flatten]
# => {"Company Name"=>"Field6", "Email"=>"Field5"}
In your view, parse the hash:
<% fields_with_values.each do |label, value| %>
l: <%= label %>
v: <%= params[value.intern] %>
<% end %>
Note that this will break if your input array is uneven, ie. a key without a value.
EDIT
As mentioned in a comment below (+1), duplicate keys will not work. Fields that have the same label as another field are no good.
fields = [["Company Name", "Field6"], ["Email", "Field5"]]
# first element in array is Label and second is param id
fields_with_values = fields.collect do |label, param_id|
# It looks like there is no need for a nested array here, so just return a Hash
{
label: label,
value: params[param_id]
}
end
#=> [{:label=>"Company Name", :value=>"gfdgfd"}, {:label=>"Email", :value=>"gfdgfd#gfd.pl"}]
It looks like you are trying to use dot syntax to get values out of a Ruby Hash similar to how you would use dot syntax for a JavaScript object (e.g. field.label). Unfortunately this doesn't work for Ruby. I wish it did because it looks very clean. For the Ruby Hash you must use an index, which is a symbol in this case: field[:label]. Your ERB code will look something like this:
# template.erb
<% fields_with_values.each do |field| %>
l: <%= field[:label] %>
v: <%= field[:value] %>
<% end %>
The easy most basic way would be:
class Foo
attr_accessors :label, :value
def initialize (label, value)
#label = label
#value = value
end
end
fields_with_values = fields.map do |field|
Foo.new(field[0], params[field[1]])
end
from here on you can make it more Ruby way with splat operator or create the objects on the fly, etc. etc.
l:
v:
I would do
fields_with_values = fields.collect do |field|
{label: field[0], value: params[field[1]}
end
And in the view
<% fields_with_values.each do |field| %>
l: <%= field[:label] %>
v: <%= field[:value] %>
<% end %>
However, lets say label is a company and value is an e-mail. If you have a class like
class Company < SomethingOrNothing
attr_accessible :name, email
# methods here
end
You could do
#companies = fields.collect do |field|
Company.new(name: field[0], email: field[1])
end
And then
<% #companies.each do |company| %>
l: <%= comapny.name %>
v: <%= company.email %>
<% end %>
However, most likely creating a new class just for that is over engineering, unless you will use this class over and over in your code.
Using Haml 3.1.4 (Separated Sally)
I am curious as to what I am doing wrong.
Why does this not show the first radio button selected?
btw, at execution, #organization.pdf_size does equal 'letter_size'
I would actually like the radio button selected based on the
#organization.pdf_size, however I am just trying to get a hard
coded selection to work atm. tyfyt
= form_for [#organization] do |f|
Select a PDF page size
= label_tag 'Letter (8.5x11)'
= f.radio_button :pdf_size, id: 'letter_size', :checked => true
= label_tag 'Half Legal (8.5x7)'
= f.radio_button :pdf_size, id: 'half_legal_size'
= f.submit 'Save', class: 'button'
I have also tried other examples I have seen on stackoverflow, in this fashion:
= f.radio_button :pdf_size, id: 'letter_size', :checked => #organization.pdf_size == 'letter_size' ? true : nil
Try this:
= f.radio_button :pdf_size, "value", id: 'letter_size', :checked => true
As documented here, the radio button needs a value before the options.
Remember to change "value" to something that makes sense for your application.
Try appending this to your link:
input_html: {checked: true}