Rails 5: find_or_create_by not saving all the params - ruby-on-rails

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!

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 rails-money undefined method `cents'

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

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: .. }

Updating two tables with one to many relationship via form

I am trying to update my two tables through my form but I am getting this error:
Started POST "/test" for ::1 at 2014-12-02 00:15:21 -0800
Processing by UsersController#create as JS
Parameters: {"utf8"=>"✓", "users"=>{"first_name"=>"sdfdsfdsf", "last_name"=>"dsfdsfds", "email"=>"3213213#hotmail.com", "phone_number"=>"23123213", "message"=>"sdfdsfsdfdsfkjsdfksdfk;adklsfjksadfksjdfklsdf"}, "commit"=>"Save Users"}
Completed 500 Internal Server Error in 1ms
ArgumentError (wrong number of arguments (1 for 0)):
app/controllers/users_controller.rb:32:in `create'
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_source.erb (2.6ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_trace.text.erb (0.4ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_request_and_response.text.erb (0.6ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/diagnostics.text.erb (12.2ms)
I have been reading examples and documentation and I think I wrote my form correctly but I think my controller is missing some aspects because I am new to rails.
Here is my schema:
ActiveRecord::Schema.define(version: 20141130075753) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "contact_requests", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "message", null: false
t.integer "user_id"
end
add_index "contact_requests", ["user_id"], name: "index_contact_requests_on_user_id", using: :btree
create_table "users", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name", null: false
t.string "last_name", null: false
t.string "email", null: false
t.string "phone_number"
end
end
Models:
class User < ActiveRecord::Base
has_many :contact_requests
validates(:first_name, presence: true)
validates(:last_name, presence: true)
validates(:email, presence: true)
accepts_nested_attributes_for :contact_requests
end
class ContactRequest < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :message, presence: true, length: { maximum: 500 }
end
user controller:
def create
if !(User.find_by(email: params[:users][:email]))
#user = User.new(user_params)
#contact_request = ContactRequest.new(contact_request_params)
#contact_request.save
#user.save
else
#contact_request = ContactRequest.new(contact_request_params)
#contact_request.save
end
end
private
def user_params
# strong_parameters, which requires us to tell Rails exactly which parameters
# we want to accept in our controllers
params.require(:users).permit(:first_name, :last_name, :email, :phone_number)
end
end
form:
<!-- contact -->
<section id="contact">
<div class="container">
<div class="title-container">Contact Us</div>
<div class="title-caption">Reach us at (415)-911-9999</div>
<%= form_for(:users, remote: true, id: "contact-form", class: "contact-input") do |f| %>
<div class="col-md-12">
<div class="col-md-6">
<div class="contact-input-margin form-group">
<%= f.text_field(:first_name, class: "form-control", placeholder: "First name")%>
</div>
<div class="contact-input-margin form-group">
<%= f.text_field(:last_name, class: "form-control", placeholder: "Last name") %>
</div>
<div class="contact-input-margin form-group">
<%= f.email_field(:email, class: "form-control", placeholder: "Email") %>
</div>
<div class="contact-input-margin form-group">
<%= f.telephone_field(:phone_number, class: "form-control", placeholder: "Phone number") %>
</div>
</div>
<div class="contact-input-margin col-md-6">
<div class="form-group">
<%= f.fields_for :contact_requests do |builder| %>
<%= f.text_area(:message, class: "form-control contact-margin", rows: "8", placeholder: "Message...") %>
<% end %>
</div>
</div>
</div>
<%= f.submit(class: "btn btn-xl") %>
<% end %>
</div>
</section>

Resources