Inconsistent indentation: 1 tab used for indentation, but the rest of the document was indented using 2 spaces - haml

= simple_form_for #pin,html: { multipart: true } do |f|
- if #pin.errors.any?
#errors
%h2
= pluralize(#pin.errors.count, "error")
prevented this Pi from saving
%ul
- #pin.errors.full_messages.each do |msg|
%li= msg
.form-group
= f.input :title, input_html: { class: 'form-control' }
.form-group
= f.input :description, input_html: { class: 'form-control' }
= f.button :submit, class: "btn btn-primary"

You have a mix of tab characters and spaces in your file. You need to stick to one or the other for haml to work. Depending on your editor you could probably fix it by setting the intendation character (most people use 2 or 4 spaces these days) and the reindent the file.

Related

How to create formtastic form with multiple language support (Internationalization)

I need to set up two languages for a single form using internationalization.
This is the proposed form page
<%= semantic_form_for #detail do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<%= f.input :dob %>
<%= f.input :gender, :as => :radio, :label => "Gender", :collection => [["Male", 'male'], ["Female", 'female']] %>
<% end %>
<%= f.actions do %>
<%= f.action :submit, :as => :input %>
<% end %>
<% end %>
This is wk.yml file
wk:
formtastic:
labels:
detail:
dob: "Data of birtha"
name: "Youre Nama"
gender: "Gendera""
This is en.yml file
en:
formtastic:
labels:
detail:
dob: "Date of Birth"
name: "Your Name"
gender: "gender"
I have added Formtastic::SemanticFormBuilder.i18n_lookups_by_default = true in formtastic.rb initializer.
I was successful in using en.yml.
I need to switch from 'en' to 'wk' and vise-verse.
How to achieve it via drop down box?
That's not something related to formstatic, but rather to your rails code.
All you have to do in order to switch to wk is
http://guides.rubyonrails.org/i18n.html
I18n.locale = :wk
In order to let your client to choose his language for the website, probably a good place to start is on this link: http://guides.rubyonrails.org/i18n.html
If all you want is to update the form (and not the rest of the website) in different languages on a user action, like selecting the language from a select box, you can use an ajax listener on the select box, that could require something like "http://www.yourwebsite.com/:locale/form/new" which will answer with an ajax action and will replace your form with the selected language (so on :locale you will pass the value of your select box for the language).

Display error messages in rails simple_form

I am new to rails and was wondering if someone could show me some light...
I have a simple form with couple of input fields and need to display field validation messages below the field name. Is there is a straightforward way to say display errors below??? or do i have to check for each field error message and create a span tag?
You can specify in your simple_form.rb initializer file with which tag your error message will be wrapped:
b.use :error, :wrap_with => { :tag => :span, :class => :error }
Also you can disable default error component on the input and print it by yourself like this:
<%= simple_form_for #user do |f| %>
<%= f.input :name, error: false %>
<%= f.error :name %>
<%= f.submit %>
<% end %>
and style your error message like you want.

simple_form - how do I create radio buttons with nested input text boxes

I'm using simple_form to render my forms and trying to get the following behavior: I want the client to choose from 3 options. In every option he supplies additional field or two.
So I'd like something like this:
Please set your preferences:
o Pay me on a specific day - [input field to get the day]
o Pay me a specific amount of money - [input field for the amount]
o Pay me on a regular basis - [radio buttons to choose between weekly/monthly basis]
I can create the radio buttons as follows, but can't add nested fields under them:
<%= simple_form_for #client, action: 'edit_payment_method' do |f| %>
<%= f.input :payment_type, label: 'Please set your preferences:',
collection: [ ['Pay me on a specific day', :specific_day],
['Pay me a specific amount of money', :specific_money],
['Pay me on a regular basis', :regular_basis]
], as: :radio_buttons %>
<%= f.button :submit, 'Submit' %>
<% end %>
What would be the best way to create the nested text boxes?
As for the fields, I don't need to send them to different controllers (per payment_type), it's fine if I send them all to one method and read the relevant values according to the payment type he chose.
Thanks! Zach
The simple_form collection_radio_buttons is likely what you want. Its options parameter accepts a block which allows you to customize what is rendered with each radio button. Take a look at the example in rdocs here.
Edited:
Here is basically what you need to do in a relatively generic way (hasn't been tested, but I'm running something similar). Put your additional controls in the partial for each radio button:
<% radio_buttons = [
{ :text => 'Pay me on a specific day', :value => :specific_day, :partial => "<textbox_partial_name>", :locals => { :any_locals => :your_partial_needs} },
{ :text => 'Pay me a specific amount of money', :value => :specific_money, :partial => "<textbox_partial_name>", :locals => { :any_locals => :your_partial_needs} },
{ :text => 'Pay me on a regular basis', :value => :regular_basis, :partial => "<radio_partial_name>", :locals => { :any_locals => :your_partial_needs} },
] %>
<%= simple_form_for #client, action: 'edit_payment_method' do |f| %>
<%= f.label t("account.update_payment_method.title") %>
<%= f.collection_radio_buttons :payment_type, (collection.collect do |r| [r[:text], r[:value], r[:partial].nil? ? "" : r[:partial], r[:locals].nil? ? {} : r[:locals]] end), :second, :first do |builder| %>
<%= builder.label{builder.radio_button(:class => 'payment_method_options') + builder.text} %>
<% unless builder.object[2].blank? %>
<%= render :partial => builder.object[2], :locals => builder.object[3] %>
<% end %>
<% end %>
<%= f.button :submit, 'Submit' %>
<% end %>
You can omit :partial for any radio button that doesn't need additional controls, along with :locals if your partial doesn't need it. There are also ways to simplify this code for your situation, but this example illustrates how to add more complex control structures to each radio button if needed.
OK.. I've managed to solve this somehow, not sure that it's the best alternative, but I'm posting it so if someone needs it in the future he at least has something to start with.
I went with creating a "regular" form using simpleform and then using JQuery to move the inner input fields (which were created regularly) next to the radio buttons.
Add JQuery support to your rails app:
add gem "jquery-rails" to your Gemfile
bundle install
rails generate jquery:install
The form I've used (regular simpleform):
Notice the class that is attached to the radio buttons and the ids that are attached to the input fields. I'll use it later to move the elements.
<%= simple_form_for #client, url: 'update_payment_data' do |f| %>
<%= f.input :payment_type, label: t('account.update_payment_method.title'),
input_html: { class: 'payment_method_options' },
collection: [ [t('account.update_payment_method.sum_based.title'), :amount],
[t('account.update_payment_method.days_in_month_based.title'), :days_in_month],
[t('account.update_payment_method.optout.title'), :optput]
], as: :radio_buttons %>
<%= f.input :payment_amount, label: "Payment amount threshold",
input_html: { id: 'payment_amount_box' } %>
<%= f.input :payment_days_in_month, label: "Payment days in month",
input_html: { id: 'payment_days_in_month_box' } %>
<%= f.button :submit, t('account.update_payment_method.update') %>
<% end %>
In the same page - the JQuery code:
<script>
$(document).ready(function() {
var amount_box = $("#payment_amount_box");
var amount_box_parent = amount_box.parent();
amount_box.detach().appendTo($(".payment_method_options:eq(0)").parent());
amount_box_parent.remove();
var dim_box = $("#payment_days_in_month_box");
var dim_box_parent = dim_box.parent();
dim_box.detach().appendTo($(".payment_method_options:eq(2)").parent());
dim_box_parent.remove();
});
</script>
I think it's pretty self-explanatory, it just looks for what is going to be the inner input fields (by id) and moves them into the appropriate place under the span that simpleform creates for each radio button.
I had to play a little bit with the css to make it look how I wanted (display:block for example), but that's more or less it.
Hope it helps.. Zach

Haml Bootstrap search form

My navbar code looks like this:
%header.navbar.navbar-fixed-top
%div.navbar-inner
%div.container
%nav
%ul.nav.pull-right
- if user_signed_in?
%li= link_to "Sign out", '#'
- else
%li= link_to "Sign in", '#'
I am trying to get my navbar to look like that in the Bootstrap navbar page as shown here, however I'm not sure how to translate
<form class="navbar-search pull-left">
<input type="text" class="search-query" placeholder="Search">
</form>
into Haml. My last attempt look like:
%header.navbar.navbar-fixed-top
%div.navbar-inner
%div.container
%nav
%ul.nav.pull-right
%form.navbar-search
%input.search-query
- { :type => "text", :placeholder => "Search" }
- if user_signed_in?
%li= link_to "Sign out", '#'
- else
%li= link_to "Sign in", '#'
While the search bar appears with the proper CSS classes, the :type => "text" and :placeholder => "Search" portions do not exist in my html when I inspect it. How can I fix this? Thanks!
== EDIT ==
Perhaps to make this clearer - I'm using this in a rails 3 app and I realize that I should probably be using form_tag, but I'm not sure how to proceed.
It should work like this:
%header.navbar.navbar-fixed-top
%nav.navbar-inner
.container
%ul.nav
- if user_signed_in?
%li= link_to "Sign out", '#'
- else
%li= link_to "Sign in", '#'
= form_tag some_path, :class => "navbar-search pull-left", :method => :get do
= text_field_tag :name, nil, :class => "search-query span3", :placeholder => "Search"
Be careful with the indentation.
I also advise you to try to start with rails app template and tutorial: http://railsapps.github.com/. As for a beginner it would be an excellent example of what and how to set up and how it should look like.

Rails 3 - how to implement changing case of descriptions based on a check_box_tag (not part of model) in before_save callback in external class

I have an rails 3 application where there are multiple registrations (diagnosis, patient, laboratory test, service, client, user, supplier). Initially these will be populated by seeding the database. The requirement is for the description codes to be mixed case (capitalised first word) when either
1. specified by the application (some configuration setting - yet to be determined)
2. specified by data entry user
At present I have a model, view & controller for Diagnosis which contains two fields:
1. code (always to be capitalised)
2. description (First word capitalised based on check_box_tag value)
Presently I am using a before_save callback in the model to implement the conversion, but I cannot get it to only work when the check_box_tag is not selected i.e. its ignoring the check_box_tag.
I have tried changing the check_box_tag to a check_box adding an attr_assessor to the model (but not the sqlite3 db as it is not required to be stored).
This didn't work either.
How do I accomplish this? How do I override the option to use a checkbox from an internal application configuration file which results in either the checkbox being 'unavailable' or not visible if the application configuration specifies not user selectable?
Model (diagnosis.rb)
require 'DescriptionHelper'
class Diagnosis < ActiveRecord::Base
attr_accessible :code, description
string_correct_case = DescriptionHelper.new([:code, :description])
validates :code, :presence => true, :length => { :minimum => 4, :maximum => 4 }
validates :description, :presence => true
before_save string_correct_case
end
Callback in DescriptionHelper.rb
class DescriptionHelper
def initialize(attribute)
#attrs_to_manage = attribute
end
def before_save(record)
#attrs_to_manage.each do |attribute|
record.send("#{attribute}=", capitaliseWords(record.send("#{attribute}")))
end
end
private
def capitaliseWords(value)
value = value.mb_chars.downcase.to_s.gsub(/\b\w/) { |first| first.upcase }
end
end
Controller (diagnoses_controller.rb)
class DiagnosesController < ApplicationController
def new
#diagnosis = Diagnosis.new
end
def create
#diagnosis = Diagnosis.new(params[:diagnosis])
if #diagnosis.save
flash[:notice] = "Diagnosis created with params [#{#diagnosis.attributes.inspect}" #for debugging, once fixed will be just 'Diagnosis created.'
redirect_to #diagnosis
else
flash[:alert] = "Diagnosis not created."
render :action => "new"
end
end
.. other controller actions - edit, show, destroy
end
View (_form.html.erb)
<%= form_for(#daignosis) do |f| %>
<div class="field">
<%= f.label :code %>
<%= f.text_field :code %>
</div>
<div class="field">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
<div class="field">
<%= check_box_tag("diagnosis_desc_dont_convert", 1, false) %><%= f.label "Leave as entered" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
When this runs currently the check_box_tag is ignored.
When adding in the model an attar_assessor :description_correctcase and changing the view to use f.check_box 'description_correctcase' this is still ignored.
How does one get this to work?
Thanks in advance from a rails aspiring developer.
Finally got a solution to the problem, after reading and re-reading various SO solutions to component parts of my question. I'm not sure its correct in terms of rails, but it works.
If you can offer me a better solution I would certainly learn from this.
Here is my solution.
Model (diagnosis.rb)
require 'DescriptionHelper'
class Diagnosis < ActiveRecord::Base
attr_accessor :do_not_correctcase
attr_accessible :code, :description, :do_not_correctcase
before_save DescriptionHelper.new([:code, :description]), :if =>
lambda { |d| d.do_not_correctcase.to_s == '0' }
validates :code, :presence => true, :length => { :minimum => 4, :maximum => 4 }
validates :description, :presence => true
end
This I referenced from the following SO solution - https://stackoverflow.com/a/6388691/1108010
Controller (diagnoses_controller.rb)
class DiagnosesController < ApplicationController
def new
#diagnosis = Diagnosis.new
end
def create
#diagnosis = Diagnosis.new(params[:diagnosis])
#diagnosis.do_not_correctcase = params[:diagnosis][:do_not_correctcase]
logger.debug "New diagnoses: #{#diagnosis.attributes.inspect}"
logger.debug "Diagnosis should be valid: #{#diagnosis.valid?}"
logger.debug "code has value #{params[:code]}"
if #diagnosis.save
flash[:notice] = "Diagnosis created with params [#{#diagnosis.attributes.inspect}" #for debugging
redirect_to #diagnosis
else
flash[:alert] = "Diagnosis not created."
render :action => "new"
end
end
.. other controller actions - edit, show, destroy
end
I also changed the view to replace the check_box_tag with a check_box.
View (_form.html.erb)
<%= form_for(#daignosis) do |f| %>
<div class="field">
<%= f.label :code %>
<%= f.text_field :code %>
</div>
<div class="field">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.check_box 'do_not_correctcase' %><%= f.label "Leave as entered" %><br />
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
So despite getting this to work I'm not clear on are the following:
When inspecting the attributes with "#{#diagnosis.attributes.inspect}".
I assume that the reason the attr_accessor variable is not included in the New diagnosis output is that it is not part of the database table and therefore Active Reocrd does not instanciate it as part of the new record with #diagnosis.new
Could someone be kind enough to confirm that.
Why does the log have no value for logger.debug "code has value #{params[:code]}"? What causes the params[:code] to be null in the logger output?
Logfile contained the following entry:
Started POST "/diagnoses" for 127.0.0.1 at 2012-03-05 09:36:38 +0000
Processing by DiagnosesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"RW/mzkhavGeaIW0hVLn0ortTnbCDlrX+FfzH4neLLsA=", "diagnosis"=>{"code"=>"tt02", "description"=>"description for tt02", "do_not_correctcase"=>"1"}, "commit"=>"Create Diagnosis"}
New diagnosis: {"code"=>"tt02", "created_at"=>nil, "description"=>"description for tt02", "updated_at"=>nil}
Diagnosis should be valid: true
code has value
I would dearly like to know what is the correct way to do all this, as I feel this is not very DRY or clean.