check box helper not updating value in database Ruby on rails - html

the checkbox helper isn't updating or inserting boolean values in the database.
A label has many attributes with values false as default and should become true when the checkbox is checked.but only the email attribute is being updated.
labelscontroller
def new
#label = current_user.labels.build
end
def create
#label = current_user.labels.build(label_params)
if #label.save
redirect_to #label
else
render 'new'
end
end
def labels_params
params.require(:label).permit(:name,:email,:avatar,:nick,:intro)
end
label/_form.html.erb
<%= form_for #label, :html => { :class => "form-horizontal label" ,multipart: true} do |f| %>
<div class="form-group", style="color: black;">
<%= f.label :name, :class => 'control-label col-lg-2' %>
<div class="col-lg-10">
<%= f.text_field :name, :class => 'form-control' %>
</div>
<%=f.error_span(:name) %>
</div> <div class="form-group", style="color: black;">
<%= f.label :email, :class => 'control-label col-lg-2' %>
<div class="col-lg-10">
<%= f.check_box :email %>
</div>
<%=f.error_span(:email) %>
</div>
<div class="form-group", style="color: black;">
<%= f.label :intro, :class => 'control-label col-lg-2' %>
<div class="col-lg-10">
<%= f.check_box :intro, checked: false %>
</div>
<%=f.error_span(:intro) %>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
labels_path, :class => 'btn btn-default' %>
</div>
</div>
<% end %>
params
developement.rb server logs
database values after the create commit
rails console output of label when i ckecked both email and intro

Related

Rails handling a list of collection_select

Pretty new to Ruby, but I'm working on a website for editing information on bus routes for a larger system. The DB has Route separate from it's list of stops, Trips. I'm trying to make the list of stops for each Route easily editable with a list of collection_select forms, where each presents a list of all of the stops to choose from. That was easy with the code below in
routes/_form.html.erb
<!-- handles the list of stops -->
<div class="stops_list" id="stops_list">
<%= f.label "Stops", :class => 'control-label'%>
<% params.merge!(:trips => {}) %>
<% puts params.inspect %>
<% trips = Trip.where('route_id = ?', #route.id).order('trips.order ASC') %>
<% #trips.each do |trip| %>
<%divId = 'stop'+trip[0].to_s %>
<div class="controls" id= <%= divId %>>
<%= f.label trip[0].to_s + '.', :class => 'control-label'%>
<%= collection_select params[:trips], trip[0].to_s, Stop.order('name ASC').all, :id, :name, {:selected => #trips[trip[0]]} %>
</div>
<% end %>
And then I update the proper tables in the DB from the routes_controller based on the data in params. I'd also like to be able to add and remove stops. I tried adding a 'remove stop' button, as below,
<%= button_to_function 'Remove stop',
'if(confirm("Really?")) {
$("#stops_list div").last().remove();
$.get("/routes/removeLastStop/'+(#route.id.to_s)+'");
}'%>
and it removes the proper collection_select form, but I then have to remove the stop from params. I tried doing an ajax call, as you can see, but then I have a new instance of the routes_controller, and the params I want to change is inaccessible. I'm not sure if I just set up the stops list wrong in the first place, or if there's a quick fix, but can anyone more experienced point me in the right direction?
EDIT:
Here's the entire form; it's pretty simple until you reach the area I've added
<%= form_for #route, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
<%= f.label :name, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :name, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :longname, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :longname, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :color, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :color, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :shape, 'Shape (KML file)', :class => 'control-label' %>
<div class="controls">
<%= f.file_field :shape, :class => 'file_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :enabled, :class => 'control-label' %>
<div class="controls">
<%= f.check_box :enabled, :class => 'checkbox' %>
</div>
</div>
<!-- handles the list of stops -->
<div class="stops_list" id="stops_list">
<%= f.label "Stops", :class => 'control-label'%>
<% params.merge!(:trips => {}) %>
<% puts params.inspect %>
<% trips = Trip.where('route_id = ?', #route.id).order('trips.order ASC') %>
<% #trips.each do |trip| %>
<%divId = 'stop'+trip[0].to_s %>
<div class="controls" id= <%= divId %>>
<%= f.label trip[0].to_s + '.', :class => 'control-label'%>
<%= collection_select params[:trips], trip[0].to_s, Stop.order('name ASC').all, :id, :name, {:selected => #trips[trip[0]]} %>
</div>
<% end %>
<%= button_to_function 'Remove stop',
'if(confirm("Really?")) {
$("#stops_list div").last().remove();
$.get("/routes/removeLastStop/'+(#route.id.to_s)+'");
}'%>
</div>
<!-- adds submit button -->
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
routes_path, :class => 'btn' %>
</div>
<% end %>
Firstly you can add to Route class:
class Route < ActiveRecord::Base
has_many :trips
end
Firstly i'd like to advise you using decorators, inserting Models in Views is not the best practice.
Secondly you can use gem 'draper' and in RouteDecorator class you can add functions for creating something you want to use or display.
Thirdly you'd better use:
<div class="controls" id="stop<%= trip[0].to_s %>">
Forthly it would be better to use paths in REST-style:
/routes/2/stop/remove
/routes/2/stop/add
Fifthly can you give code of all form?
Probably we need to refactor it to look better and be easier for understanding.

How do I nest models using a form_tag in Rails 4?

I've got a form to add SaleQualifiers to my app - which works fine when I'm using:
<%= form_for(#sale_qualifier, :html => {role: :form, 'data-model' => 'sale_qualifier'}, remote: true) do |f| %>
The problem with form_for is that I want to put the form inline within a table row in my view - so as a method to get around that I'm now using:
<%= form_tag('/sale_qualifiers', method: :post, remote: true) do -%>
<%= fields_for :sale_qualifier do |ff| %>
This is working fine for most of the fields I need to generate, but I've got a nested attribute field for Answer (Answer belongs_to SaleQualifier). This is not generating the right field names in the view, and as a result when I go to save the object this way I don't capture the answer_attributes.
Here's the full working form using form_for:
<div class="panel panel-default">
<%= form_for(#sale_qualifier, :html => {role: :form, 'data-model' => 'sale_qualifier'}, remote: true) do |f| %>
<% if #sale_qualifier.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#sale_qualifier.errors.count, "error") %> prohibited this answer from being saved:</h2>
<ul>
<% #sale_qualifier.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="panel-body">
<div class="col-sm-6">
<h2><%= #question.question_text %></h2>
<% unless #question.id == 1 %>
<p><%= link_to('Back', edit_sale_qualifier_path(id: #prior_sale_qualifier), data: { disable_with: "Loading..." }, :remote => true) %></p>
<% end %>
</div>
<div class="col-sm-6">
<div class="form-group">
<%= f.hidden_field :sales_opportunity_id, :value => #sales_opportunity.id %>
</div>
<div class="form-group">
<%= f.hidden_field :question_id, :value => #question.id %>
</div>
<% unless #question.id == 1 %>
<div class="form-group">
<%= f.hidden_field :prior_question_id, :value => #prior_question_id %>
</div>
<% end %>
<%= f.fields_for :answer do |answer| %>
<div class="form-group">
<% if #question.answer_type == 'Text Field' %>
<%= answer.text_area :answer_text, :placeholder => "Enter your answer", :class => "form-control"%>
<% end %>
<% if #question.answer_type == 'Datetime' %>
<div class='input-group date' id='datetimepicker' data-date-format="YY.MM.DD">
<%= answer.text_field :answer_text, class: "form-control", data: { date_format: 'YYYY/MM/DD' }, :placeholder => "YYYY/MM/DD" %>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<% end %>
<% if #question.answer_type == 'Boolean' %>
<%= answer.select :answer_text, [['Yes', true], ['No', false]] %>
<% end %>
<% if #question.answer_type == 'Update' || #question.answer_type == 'Result' %>
<%= answer.hidden_field :answer_text, :value => "Updated" %>
<% end %>
<span class="warning-block"></span>
<span class="help-block"></span>
</div>
<% end %>
<% if #question.answer_type == 'Update' || #question.answer_type == 'Result' %>
<div class="actions">
<%= f.submit "Done", class: "btn btn-large btn-success", data: { disable_with: "Submitting..." }, autocomplete: 'off' %>
</div>
<% else %>
<div class="actions">
<%= f.submit "Submit", class: "btn btn-large btn-success", data: { disable_with: "Submitting..." }, autocomplete: 'off' %>
</div>
<% end %>
<% end %>
</div>
</div>
</div>
Here's the code which does not work using form_tag:
<%= form_tag('/sale_qualifiers', method: :post, remote: true) do -%>
<%= fields_for :sale_qualifier do |ff| %>
<%= ff.hidden_field :sales_opportunity_id, :value => #sales_opportunity.id %>
<%= ff.hidden_field :question_id, :value => #question.id %>
<tr>
<td><%= #question.question_text %></td>
<td>
<%= ff.fields_for :answer do |answer| %>
<% if #question.answer_type == 'Text Field' %>
<%= answer.text_area :answer_text%>
<% end %>
<% if #question.answer_type == 'Datetime' %>
<div class='input-group date' id='datetimepicker' data-date-format="YY.MM.DD">
<%= answer.text_field :answer_text, class: "form-control", data: { date_format: 'YYYY/MM/DD' }, :placeholder => "YYYY/MM/DD" %>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<% end %>
<% if #question.answer_type == 'Boolean' %>
<%= answer.select :answer_text, [['Yes', true], ['No', false]] %>
<% end %>
<% end %>
</td>
<td>
<%= ff.submit "Submit", class: "btn btn-large btn-success", data: { disable_with: "Submitting..." }, autocomplete: 'off' %>
</td>
</tr>
<% end %>
<% end %>
For completeness, the issue I'm having is that the generated html for the working code creates the following field:
textarea id="sale_qualifier_answer_attributes_answer_text" name="sale_qualifier[answer_attributes][answer_text]"
The broken code creates the following html:
Textarea id="sale_qualifier_answer_answer_text" name="sale_qualifier[answer][answer_text]"
So how can I get the html output to show "sale_qualifier[answer_attributes][answer_text]" rather than "sale_qualifier[answer][answer_text]" in this instance using form_tag?
In multiple nested forms the fields_for tag will be called against
right parent and attributes conventions should be followed right otherwise
it renders the form attributes wrong and results in errors.
<%= form_tag('/sale_qualifiers', method: :post, remote: true) do -%>
<%= fields_for :sale_qualifier do |ff| %>
<%= ff.fields_for :answer_attributes do |answer| %>
Above flow will be the right one & will generate attributes as they should be.

Do Devise forms require a label for each textfield?

Does Devise require a label for each textfield in its forms (ie: registration/new)?
When i delete the label in my code, ie:"<%= f.label :name %>", the textfield also disappears on the page. I want to show the textfield, but not the label.
devise/registrations/new.html.erb
<div class="row">
<div class="col-md-8">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="form-group>
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: 'form-control', placeholder: 'Name' %>
</div>
<div class="form-group>
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control', placeholder: 'Email' %>
</div>
<div class="form-group>
<%= f.label :password %>
<%= f.text_field :password, class: 'form-control', placeholder: 'Password' %>
</div>
<div class="form-group>
<%= f.label :password_confirmation %>
<%= f.text_field :password_confirmation, class: 'form-control', placeholder: 'Confirm password' %>
</div>
<div class="form-group">
<%= f.submit "Sign up", class: 'btn btn-success' %>
</div>
<div class="form-group">
<%= render "devise/shared/links" %>
</div>
<% end %>
</div>
</div>
After deleting label
Before deleting label
I've read its bad practice to exclude a label outside of a a textfield in a form, but Facebook does it ;)
I'm still new to RoR and any guidance is appreciated.
Does Devise require a label for each textfield
No.
Devise is a gem.
It's built using the same helpers and code as every other Ruby/Rails app. It does not have any special requirements to use labels.
In fact, the form helpers of Rails, and indeed every other helper, outputs vanilla HTML. If you can get away with not having labels in html, you can do it with your form helper.
Here's our code for a devise registration form (in HAML):
#app/views/devise/registrations/new.haml
.authenticate
= render "devise/shared/title"
= simple_form_for(User.new, as: resource_name, url: registration_path(resource_name)) do |f|
- if flash[:error]
.form-errors= flash[:error]
= f.error_notification
.form-inputs
= f.input :email, required: true, autofocus: true, placeholder: "Email"
%hr
= f.input :password, required: true, placeholder: "Password"
= f.input :password_confirmation, required: true, placeholder: "Confirm"
.form-actions
.bar
= link_to "", "#", rel: "submit", class: "ion-forward", title: "Register", data: { placement: "right" }
= render "devise/shared/links"
You should try the following:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= f.text_field :name, autofocus: true, class: 'form-control', placeholder: 'Name' %>
<%= f.text_field :email, class: 'form-control', placeholder: 'Email' %>
<%= f.text_field :password, class: 'form-control', placeholder: 'Password' %>
<%= f.text_field :password_confirmation, class: 'form-control', placeholder: 'Confirm password' %>
<%= f.submit "Sign up", class: 'btn btn-success' %>
<%= render "devise/shared/links" %>
<% end %>
Remove any HTML elements to make sure they're not preventing Rails from showing the elements properly. If it works, you'll be able to rebuild the HTML and CSS to see what the problem is.

Undefined method `error_span' - Rails Project

I am creating a job portal application in Rails 4.1 using Ruby 1.9
The application initially was running fine, but unexpectedly an error popped up. The jobs subdirectory in the views directory contains two files new.html.erb and _form.html.erb(this is a partial file). While rendering the new file, the partial file is also rendered from the new file.
But, the application is showing the following error in Rubymine
ERROR DETAILS:
"NoMethodError in Jobs#new"
Showing E:/RailsProject/Old/FinalSubm/jobportal/app/views/jobs/_form.html.erb where line #23 raised:
undefined method `error_span' at line 23
20 <div class="controls">
21 <%= f.text_field :title, :class => 'form-control' %>
22 </div>
23 <%= error_span(#job[:title]) %>
24 </div>
25 <div class="control-group">
26 <%= f.label :description, :class => 'control-label' %>
Trace of template inclusion: app/views/jobs/new.html.erb
Rails.root: E:/RailsProject/Old/FinalSubm/jobportal
Application Trace | Framework Trace | Full Trace
app/views/jobs/_form.html.erb:23:in block in _app_views_jobs__form_html_erb__604570268_42022236'
app/views/jobs/_form.html.erb:1:in_app_views_jobs__form_html_erb__604570268_42022236' app/views/jobs/new.html.erb:5:in `_app_views_jobs_new_html_erb___144564004_42034104'
The following is the code written for E:/RailsProject/Old/FinalSubm/jobportal/app/views/jobs/_form.html.erb
<%= form_for #job, :html => { :class => "form-horizontal job" } do |f| %>
<% if #job.errors.any? %>
<div id="error_expl" class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title"><%= pluralize(#job.errors.count, "error") %> prohibited this job from being saved:</h3>
</div>
<div class="panel-body">
<ul>
<% #job.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<div class="control-group">
<%= f.label :title, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :title, :class => 'form-control' %>
</div>
<%= error_span(#job[:title]) %>
</div>
<div class="control-group">
<%= f.label :description, :class => 'control-label' %>
<div class="controls">
<%= f.text_area :description, :class => 'form-control' %>
</div>
<%= error_span(#job[:description]) %>
</div>
<div class="control-group">
<%= f.label :tag1, :class => 'control-label' %>
<div class="controls">
<%= f.select :tag1, options_for_select(%w[Internship Full-Time Part-Time Co-Op Contractor]) %>
</div>
<%= error_span(#job[:tag1]) %>
</div>
<div class="control-group">
<%= f.label :tag2, :class => 'control-label' %>
<div class="controls">
<%= f.select :tag2, options_for_select(%w[Work-From-Home Office]) %>
</div>
<%= error_span(#job[:tag2]) %>
</div>
<div class="control-group">
<%= f.label :tag3, :class => 'control-label' %>
<div class="controls">
<%= f.select :tag3, options_for_select(%w[US-Citizen Non-US-Citizen]) %>
</div>
<%= error_span(#job[:tag3]) %>
</div>
<div class="control-group">
<%= f.label :category, :class => 'control-label' %>
<div class="controls">
<%= f.select :category_name, Category.all.collect{ |c| [c.name, c.id]} %>
</div>
<%= error_span(#job[:category_name]) %>
</div>
<div class="control-group">
<%= f.label :deadline, :class => 'control-label' %>
<div class="controls">
<%= f.date_select :deadline, :class => 'form-control' %>
</div>
<%= error_span(#job[:deadline]) %>
</div>
<!-- <div class="control-group">
<%= f.label :employer_id, :class => 'control-label' %>
<div class="controls">
<%= f.number_field :employer_id, :class => 'form-control' %>
</div>
<%= error_span(#job[:employer_id]) %>
</div>
<%= f.hidden_field :employer_id %>
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
jobs_path, :class => 'btn btn-default' %>
<% end %>
The following is the code written for E:/RailsProject/Old/FinalSubm/jobportal/app/views/jobs/new.html.erb
<%- model_class = Job -%>
<div class="page-header">
<h1><%=t '.title', :default => [:'helpers.titles.new', 'New %{model}'], :model => model_class.model_name.human.titleize %></h1>
</div>
<%= render :partial => 'form' %>
The program was running fine a couple of days back, no changes have been made to the code since then, apart from restarting the rails server. I am trying to figure out where this error popped from. To solve this error should I define the method error_span in Jobs#new controller ?. What should be written in it ? OR Should I remove the error_span statement from the views, but this would imply that many changes would have to be made in the code, since I have 8 to 10 more files where the partial file mentioning the html statement needs to be changed.
If you're using twitter-bootstrap-rails (which is where I'm guessing the error_span method comes from).
Try using the latest code by putting in your Gemfile:
gem 'twitter-bootstrap-rails', :git => 'https://github.com/seyhunak/twitter-bootstrap-rails.git', :branch => 'master'
Because it looks like they fixed this method a few weeks ago.
more info:https://github.com/seyhunak/twitter-bootstrap-rails/pull/795
twitter-bootstrap-railshas a bug in lib/generators/bootstrap/themed/templates/
<%%= error_span(#<%= resource_name %>[:<%= column.name %>]) %>
change to
<%%= f.error_span(:<%= column.name %>) %>
.erb && slim templete has the same bug.
here is a fixed version
Based on #NoelProf's answer, I changed my Gemfile:
gem 'twitter-bootstrap-rails', '>= 3.2.0', '< 3.2.2'
This will not install the version 3.2.2.
I restarted the server and the error_span problem has been gone.

1 error(s) on assignment of multiparameter attributes from date

I am getting this error
1 error(s) on assignment of multiparameter attributes
And I am pretty sure it is from the date_selector.
Here is my model
class Order < ActiveRecord::Base
attr_accessor :card_type, :card_number, :card_verification,
:card_expires_on # I do not have these fields in my database
attr_accessible :cart_id, :card_expires_on, :card_type, :first_name,
:ip_address, :last_name,:card_number, :card_verification, :zip, :address,
:state, :city
def credit_card
#credit_card ||= ActiveMerchant::Billing::CreditCard.new(
:brand => card_type,
:number => card_number,
:verification_value => card_verification,
:month => card_expires_on.month,
:year => card_expires_on.year,
:first_name => first_name,
:last_name => last_name
)
end
end
And the part of the controller that is involved
def create
#user = current_user
#cart = current_cart
#order = #cart.build_order(params[:order]) # here is where the error is
#order.user_id = #user.id
#order.ip_address = request.remote_ip
...
end
Here is the cart Model
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
has_one :order
belongs_to :user
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(:product_id => product_id)
end
current_item
end
def total_price
line_items.to_a.sum { |item| item.total_price}
end
def total_price_in_cents
return Integer(total_price * 100)
end
end
And heres the order form that goes along with order.rb...Thank you again for the help!!!
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name %>
</div>
<div class="field">
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.label :address %>
<%= f.text_field :address %>
</div>
<div class="field">
<%= f.label :city %>
<%= f.text_field :city %>
</div>
<div class="field">
<%= f.label :state %>
<%= f.select :state, #order.us_states %>
</div>
<div class="field">
<%= f.label :zip %>
<%= f.text_field :zip %>
</div>
<div class ="field">
<%= f.label :card_type %> <br />
<%= f.select :card_type, [["Visa", "visa"], ["MasterCard", "master"], ["Discover", "discover"], ["American Express", "american_express"]] %>
</div>
<div class="field">
<%= f.label :card_number %><br />
<%= f.text_field :card_number %>
</div>
<div class="field">ry
<%= f.label :card_verification, "Card Verification (CVV)" %><br />
<%= f.text_field :card_verification %>
</div>
<div class="field">
<%= f.label :card_expires_on %><br />
<%= f.date_select :card_expires_on, :discard_day => true, :start_year => Date.today.year, :end_year => (Date.today.year+10), :add_month_numbers => true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
Have you tried #order = #cart.orders.new(params[:order])?
In the case of a one-to-one relationship between an order and a cart, that would be:
#cart.order.new(params[:order])