Rails rails-money undefined method `cents' - ruby-on-rails

I am attempting to implement money-rails and I have run into the following error:
undefined method `cents' for "1,000.00":String
I followed this tutorial to get a "fancy" currency input field.
DB schema:
t.integer "balance_cents", default: 0, null: false
t.string "balance_currency", default: "USD", null: false
Model:
monetize :balance_cents, as: :balance, allow_nil: :true, :numericality => { :greater_than_or_equal_to => 0}
def initialize(attributes = {})
super
#balance = attributes[:balance]
end
Form:
<%= form_for(#asset, url: assets_new_path) do |f| %>
<%= f.label :balance, "Balance / Value ($)" %>
<%= f.number_field :balance, data: { role: 'money', a_sep: ',', a_dec: '.' }, class: 'form-control' %>
Controller:
def create
#asset = Asset.new(asset_params)
if #asset.save
flash[:success] = "New asset created successfully."
redirect_to assets_path
else
...
end
end
def asset_params
params.require(:asset).permit(:balance)
end
Should I be setting up the :balance input field another (better) way?

According to the Rails Guides the best way to do it in the after_initialize callback.

Use balance_satangs for your column instead of balance_cents

Related

Rails create does not save params from checkbox

I am creating a website where a user (interviewer) can create a position (a job opening).
Even if the params are sent, my create action does not save them except for the current_user.
This is what I send:
positions_controller.rb
def new
#position = Position.new
end
def create
#position = Position.new(position_params)
#position.interviewer = current_interviewer
if #position.save
redirect_to position_path(#position)
flash[:success] = "You created a new position/opening"
else
render :new
end
raise
end
private
def set_position
#position = Position.find(params[:id])
end
def position_params
params.require(:position).permit(:title, :skills, :interviewer)
end
end
_form.html.erb
<%= simple_form_for [#interviewer, #position] do |f| %>
<%= f.input :title, required:true %>
<%= f.input :skills, as: :check_boxes, collection:[
['Python', "python"],
['Java', "java"],
['JavaScript', "javascript"],
['Ruby', "ruby"],
['C++', "c++"],
['Node.js', "node"],
['React', "react"],
['Django', "django"],
['Rails', "rails"],
['SQL', "sql"],
['Doker', "doker"],
['AWS', "aws"],
['Vue.js', "vue"],
['Marketing', "Marketing"],
['HR', "hr"],
['Finance', "finance"],
['IT', "it"],
], input_html: { multiple: true } %>
<%= f.submit "Submit position", class: "btn btn-primary" %>
<% end %>
position.rb
class Position < ApplicationRecord
validates :title, presence: true
belongs_to :interviewer
end
schema
create_table "positions", force: :cascade do |t|
t.string "title"
t.bigint "interviewer_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "candidate_id"
t.string "candidatures", default: [], array: true
t.string "skills"
t.index ["candidate_id"], name: "index_positions_on_candidate_id"
t.index ["interviewer_id"], name: "index_positions_on_interviewer_id"
end
My alternative was to replace the create code with:
#position = current_interviewer.positions.new(position_params)
but it still does not work.
Since you have a input_html: { multiple: true } for the params skills, you need to add the following in positions_controller.rb:
def position_params
params.require(:position).permit(:title, :interviewer, :candidate, skills:[])
end
Basically, your skills will be saved as an array if you allow input_html: { multiple: true } for a collection
In addition, you are not passing any params for candidate
In your table, you have interviewer_id but in your permitted params you have interviewer.
Change your params to permit interviewer_id instead.
Also, in your form you have <%= f.input :title, required:true %> Presence is required by default (at least with simple_form). You don't need to declare it in the form, but you should still keep it in your Model.

Rails 5: find_or_create_by not saving all the params

I have a form that should send info. One of the inputs is "empresa_id", and it's represented by a collection. I have checked in the server the form send the information I want. The thing is this field (only that one) is not saved when I run find_or_create_by. I've checked strong params and everything seem fine there.
SuscriptorsController
def create
#suscriptor = Suscriptor.new(suscriptor_params)
byebug #In this point #suscriptor.empresa_id has a correct value
if !#suscriptor.valid?
flash[:error] = "El email debe ser válido"
render 'new'
else
#suscriptor = Suscriptor.find_or_create_by(email: #suscriptor.email)
if #suscriptor.persisted?
if (#suscriptor.email_confirmation == true)
flash[:notice] = "Ya estás registrado/a"
redirect_to root_path
else
SuscriptorMailer.registration_confirmation(#suscriptor).deliver
end
else
flash[:error] = "Ha ocurrido un error. Contáctanos desde la sección contacto y explícanos"
render 'new'
end
end
private
def suscriptor_params
params.require(:suscriptor).permit(:email, :email_confirmation, :token_confirmation, :subtitle, :empresa_id)
end
Form view
<%= simple_form_for(#suscriptor) do |f| %>
<div class="input-group">
<div class="col-md-12">
<div class="form-group text">
<%= f.input :email, class: "form-control", placeholder: "tucorreo#email.com", required: true %>
<%= f.invisible_captcha :subtitle %>
<small id="emailHelp" class="form-text text-muted">Lo guardaremos y usaremos con cuidado.</small>
<%= f.input :empresa_id, collection: Empresa.all %>
</div>
<div class="input-group-append">
<%= f.submit "¡Hecho!", class: "btn btn-primary" %>
</div>
</div>
<% end %>
schema.rb
create_table "suscriptors", force: :cascade do |t|
t.string "email"
t.boolean "email_confirmation"
t.string "token_confirmation"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "empresa_id"
end
suscriptor.rb
class Suscriptor < ApplicationRecord
belongs_to :empresa, optional: true
before_create :confirmation_token
attr_accessor :subtitle
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, format: { with: VALID_EMAIL_REGEX }
def confirmation_token
if self.token_confirmation.blank?
self.token_confirmation = SecureRandom.urlsafe_base64.to_s
end
end
end
In your find_or_create_by, your pass only the #suscriptor.email, and reassing the #suscriptor variable with the created suscriptor.
According API dock, you should pass a block to 'create with more parameters':
Suscriptor.find_or_create_by(email: #suscriptor.email) do |suscriptor|
suscriptor.empresa_id = #suscriptor.empresa_id
end
Be careful to not reassign #suscriptor variable before use the parameters.
You can read more about find_or_create_by in https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by
Hope this helps!

Rails Multi-step form

I'm writing a quiz app with rails 5. I have got a multi-step form for question building.
Models:
class Mcq < ApplicationRecord
attr_accessor :option_count
has_many :options, dependent: :destroy
belongs_to :quiz
accepts_nested_attributes_for :options
validates :question_text, presence: true
end
class Option < ApplicationRecord
belongs_to :mcq, optional: true
validates :option_text, presence: true
end
Schema:
create_table "mcqs", force: :cascade do |t|
t.string "question_text"
t.boolean "required"
t.boolean "multiselect"
t.integer "quiz_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "options", force: :cascade do |t|
t.string "option_text"
t.integer "mcq_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
The first page is for question setup and has the following fields:
Option Count
Required (Yes / No)
No of options that can be selected (Single / Multiple)
The second page is for options and has the following fields:
Question Text
Nested Form for Options
Controller:
class McqsController < ApplicationController
def new
session[:current_step] ||= 'setup'
session[:mcq_params] ||= {}
#current_step = session[:current_step]
#quiz = Quiz.find(params[:quiz_id])
#mcq = Mcq.new(session[:mcq_params])
if session[:current_step] == 'options'
#option_count = session[:mcq_params]['option_count']
#option_count.times { #mcq.options.build }
end
end
def create
if params[:previous_button]
session[:current_step] = 'setup'
redirect_to new_quiz_mcq_path
elsif session[:current_step] == 'setup'
save_session(params[:mcq])
redirect_to new_quiz_mcq_path
elsif session[:current_step] == 'options'
#mcq = Mcq.new(whitelisted_mcq_params)
#mcq.quiz_id = params[:quiz_id]
#quiz = Quiz.find(params[:quiz_id])
if #mcq.save
session[:current_step] = session[:mcq_params] = nil
redirect_to quiz_new_question_path(#mcq.quiz_id)
else
#current_step = session[:current_step]
render :new
end
end
end
private
def whitelisted_mcq_params
params.require(:mcq)
.permit(:question_text, :multiselect, :required, options_attributes: [:option_text])
end
def save_session(mcq_params)
session[:mcq_params][:option_count] = mcq_params[:option_count].to_i
session[:mcq_params][:required] = mcq_params[:required]
session[:mcq_params][:multiselect] = mcq_params[:multiselect]
session[:current_step] = 'options'
end
end
The above solution works, but the code is messy and difficult to understand. I came across this railscasts episode which does something similar in a cleaner way. I've updated my code as follows:
class Mcq < ApplicationRecord
has_many :options, dependent: :destroy
belongs_to :quiz
attr_writer :current_step
attr_accessor :option_count
accepts_nested_attributes_for :options
validates :question_text, presence: true
def current_step
#current_step || steps.first
end
def steps
%w[setup options]
end
def next_step
self.current_step = steps[steps.index(current_step)+1]
end
def previous_step
self.current_step = steps[steps.index(current_step)-1]
end
def last_step?
current_step == steps.last
end
end
class McqsController < ApplicationController
def new
session[:mcq_params] ||= {}
#quiz = Quiz.find(params[:quiz_id])
#mcq = Mcq.new(session[:mcq_params])
#mcq.current_step = session[:mcq_step]
end
def create
#quiz = Quiz.find(params[:quiz_id])
session[:mcq_params].deep_merge!(params[:mcq]) if params[:mcq]
#mcq = Mcq.new(session[:mcq_params])
#option_count = session[:mcq_params]['option_count']
#option_count.times { #mcq.options.build }
#mcq.quiz_id = params[:quiz_id]
#mcq.current_step = session[:mcq_step]
if params[:previous_button]
#mcq.previous_step
elsif #mcq.last_step?
#mcq.save if #mcq.valid?
else
#mcq.next_step
end
session[:mcq_step] = #mcq.current_step
if #mcq.new_record?
render "new"
else
session[:mcq_step] = session[:mcq_params] = nil
redirect_to edit_quiz_path(#mcq.quiz_id)
end
end
end
But each time the second page is shown, the no of fields for options doubles or in case of invalid entry only the field for question_text is shown. How do I show the options correctly? Should I just go with my first solution? I'm new to rails and don't know much about the best practices.
Edited :
new.html.erb
<div class="sub-heading">Add a Multiple Choice Question:</div>
<%= render "mcq_#{#mcq.current_step}", quiz: #quiz, mcq: #mcq %>
_mcq_setup.html.erb
<div class="form-container">
<%= form_for [quiz, mcq] do |f| %>
<div class="form-row">
<div class="response-count">How many options should the question have?</div>
<%= f.select(:option_count, (2..5)) %>
</div>
<div class="form-row">
<div class="response-count">How many options can be selected?</div>
<div class="option">
<%= f.radio_button :multiselect, 'false', checked: true %>
<%= f.label :multiselect, 'Just One', value: 'false' %>
</div>
<div class="option">
<%= f.radio_button :multiselect, 'true' %>
<%= f.label :multiselect, 'Multiple', value: 'true' %>
</div>
</div>
<div class="form-row">
<div class="response-count">Is the question required?</div>
<div class="option">
<%= f.radio_button :required, 'true', checked: true %>
<%= f.label :required, 'Yes', value: 'true' %>
</div>
<div class="option">
<%= f.radio_button :required, 'false' %>
<%= f.label :required, 'No', value: 'false' %>
</div>
</div>
<%= f.submit "Continue to the Next Step" %>
<% end %>
</div>
_mcq_options.html.erb
<%= form_for [quiz, mcq] do |f| %>
<%= f.label :question_text, 'What is your question?' %>
<%= f.text_field :question_text %>
<%= f.fields_for :options do |option_fields| %>
<%= option_fields.label :option_text, "Option #{option_fields.options[:child_index] + 1}:" %>
<%= option_fields.text_field :option_text %>
<% end %>
<%= f.hidden_field :multiselect %>
<%= f.hidden_field :required %>
<%= f.submit "Add Question" %>
<%= f.submit "Back to previous step", name: 'previous_button' %>
<% end %>
You may look in direction of state_machine. By using that you can use your steps as states of state machine and use its ability to define validations that only active for given states (look here in state :first_gear, :second_gear do) so fields that required on second step will be not required on first. Also, it'll allow you to avoid complex checks for the step you currently on (because the state will be persisted in a model) and will be pretty easy to extend with more steps in a future.

5 form elements present, but only 4 are saving to the database. Rails

I am having a problem with my database. I am able to save all the elements of my form into the database but it is leaving out ":captcha" for some reason. :email, :first_name, :last_name and :user_message are all saving, but :captcha is not.
HTML form views/pages/index.html.erb
<%= form_for(#message) do |f| %>
<%= f.text_field :first_name, :class => "message_name_input message_input_default", :placeholder => " First Name" %>
<br><br>
<%= f.text_field :last_name, :class => "message_name_input message_input_default", :placeholder => " Last Name" %>
<br><br>
<%= f.text_field :email, :required => true, :class => "message_email_input message_input_default", :placeholder => " * Email" %>
<br><br>
<%= f.text_area :user_message, :required => true, :class => "message_user-message_input", :placeholder => " * Write a message" %><br><br>
<%= f.text_field :captcha, :required => true, :name => "captcha", :class => "message_input_default", :placeholder => " * #{#a} + #{#b} = ?" %><br><br>
<div id="RecaptchaField2"></div>
<%= f.submit "Send", :class => "messages_submit_button" %>
<% end %>
Pages Controller
class PagesController < ApplicationController
def index
#message = Message.new
#a = rand(9)
#b = rand(9)
session["sum"] = #a + #b
end
end
Messages Controller
class MessagesController < ApplicationController
def show
end
def new
#message = Message.new
end
def create
#message = Message.new(message_params)
if params["captcha"].to_i == session["sum"] && #message.save!
UserMailer.welcome_email(#message).deliver_now
redirect_to '/message_sent'
else
redirect_to '/'
end
end
private
def message_params
return params.require(:message).permit(:first_name, :last_name, :email, :user_message, :captcha)
end
end
Messages Migration
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.string :captcha
t.string :first_name
t.string :last_name
t.string :email
t.string :user_message
t.timestamps null: false
end
end
end
Schema
ActiveRecord::Schema.define(version: 20150822040444) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "messages", force: :cascade do |t|
t.string "captcha"
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "user_message"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
Routes
Rails.application.routes.draw do
resources :pages
resources :messages
resources :admins
get '/' => 'pages#index'
get '/new' => 'messages#new'
post '/message_sent' => 'messages#create'
get '/message_sent' => 'messages#show'
end
EDITED Attempted this code, but instead of saving 4 elements, it executes the "else" statement and redirects as if it is not being saved at all.
Messages Controller
class MessagesController < ApplicationController
def show
end
def new
#message = Message.new
end
def create
#message = Message.new(message_params)
if params[:message][:captcha].to_i == session["sum"] && #message.save!
UserMailer.welcome_email(#message).deliver_now
redirect_to '/message_sent'
else
redirect_to '/'
end
end
private
def message_params
return params.require(:message).permit(:first_name, :last_name, :email, :user_message, :captcha)
end
end
Remove name attribute from here:
<%= f.text_field :captcha, :required => true, :name => "captcha", :class => "message_input_default", :placeholder => " * #{#a} + #{#b} = ?" %><br><br>
It happens because name parameter is generated by rails itself, and it's responsible to structure your query. Thus this erb line:
<%= f.text_field :first_name %>
Will generate this html:
<input type="text" name="message[first_name]">
And when you submit form it will produce query like this
{ message: { first_name: 'value_of_input' } }
But you provided custom name that overridden default behaviour and produces requests like this:
{ captcha: 'captcha_val', message: { first_name: 'some_val1', last_name: 'some_val2', ... } }
Then you extract message params from params:
def message_params
params.
require(:message).
permit(:first_name, :last_name, :email, :user_message, :captcha)
end
Finally you create message with this hash:
{ first_name: .., last_name: .., email: .., user_message: .. }

Error: undefined method `each' for "1":String

I'm trying to associate a model Thing with another Thing on my things/new form. Each Thing has_many :things through a join table :related_things.
When I submit the form, I get this error:
NoMethodError in ThingsController#create
undefined method `each' for "1":String
Where did I go wrong with my code?
Thing model: I put asterisks around the line with the error message.
class Thing < ActiveRecord::Base
has_many :related_things
has_many :things, :through => :related_things
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "30x30!" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
def related_things
related_thing_ids = RelatedThing.
where("thing_a_id = ? OR thing_b_id = ?", self.id, self.id).
map { |r| [r.thing_a_id, r.thing_b_id] }.
flatten - [self.id]
Thing.where(id: related_thing_ids)
end
def related_thing_ids=(ids)
***ids.each do |id|***
record = RelatedThing.where(thing_a_id: self.id, thing_b_id: id).first
record ||= RelatedThing.where(thing_a_id: id, thing_b_id: self.id).first
record ||= RelatedThing.create!(thing_a_id: self.id, thing_b_id: id)
end
end
end
RelatedThing model:
class RelatedThing < ActiveRecord::Base
has_many :things
end
Things controller:
class ThingsController < ApplicationController
def show
#thing = Thing.find(params[:id])
#related_thing = RelatedThing.all
#thing.things.build
end
def new
#thing = Thing.new
#things = Thing.all
end
def create
#thing = Thing.new(thing_params)
if #thing.save
redirect_to #thing
else
render 'new'
end
end
private
def thing_params
params.require(:thing).permit(:name, :avatar, :related_thing_ids)
end
end
Things/new.html.erb:
<h1>Add Something!</h1>
<p>
<%= form_for #thing, :url => things_path, :html => { :multipart => true } do |f| %>
<%= f.text_field :name, :placeholder => "Name of the thing" %>
<br>
<%= f.label :related_things %>
<%= f.collection_select :related_thing_ids, Thing.all, :id, :name %>
<br>
<%= f.label :display_picture %>
<%= f.file_field :avatar %>
<br>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</p>
Schema.rb:
ActiveRecord::Schema.define(version: 20141016190146) do
create_table "related_things", force: true do |t|
t.integer "thing_a_id"
t.integer "thing_b_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "things", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
end
end
I'm using Rails 4.0.10.
Try Array(ids).each ..., which convert any object in an array and respond to :each
~ (main) > Array(nil)
=> []
~ (main) > Array([])
=> []
~ (main) > Array('')
=> [""]
~ (main) > Array(1)
=> [1]
See Kernel#Array

Resources