I have a parent table and in it there is a boolean field admin. I have a admin signup page where i want a hidden field for admin to set as true. Please help. I have tried the step below. please correct it as it is not working.
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#parent, :html => { multipart: true, class: "form-horizontal", role: "form"}) do |f| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :email, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.email_field :email, class: "form-control", placeholder: "Enter email", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password, class: "form-control", placeholder: "Enter password", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password_confirmation, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password_confirmation, class: "form-control", placeholder: "Re-enter password", required: true %>
</div>
</div>
<%= f.hidden_field :admin, :value => true %>
<div class="form-group">
<div class="col-sm-10">
<%= f.submit 'Sign up', class: 'btn btn-primary btn-lg' %>
</div>
</div>
<% end %>
</div>
</div>
Parent controller
def addusers
#parent=Parent.new
end
Updated parent controller
def new
#parent = Parent.new
#parent.secondaryparents.build
add_breadcrumb "Home", :root_path
add_breadcrumb "Sign up"
end
def addusers
#parent=Parent.new
end
def create_users
#parent=Parent.new(parent_params)
#parent.admin = true
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please ask user to confirm email address to continue"
redirect_to main_admin_path
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to main_admin_path
end
end
def create
#parent = Parent.new(parent_params)
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please confirm your email address to continue"
redirect_to root_path(#parent)
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to signup_path
end
end
Routes
resources :parents do
resources :children do
resources :fundings
end
end
end
get 'signup', to:'parents#new'
get 'login', to: 'sessions#new'
get 'usersignup', to:'parents#addusers'
post 'usersignup', to:'parents#create_users'
resources :parents, except: [:new] do
member do
get :confirm_email
end
end
Remove hidden line from html page, no need it f.hidden_field :admin, :value => true
Form_for
form_for(#parent, url: usersignup_path,
:html => { multipart: true, class: "form-horizontal", role: "form"}) do |f|
Add to routes:
post 'usersignup', to:'parents#create_users'
Controller:
def create_users
#parent = Parent.new(parent_params)
#parent.admin = true
if #parent.save
#do yr logic here
else
redirect_back(fallback_location: "/", flash: { danger: "smth went wrong.." })
end
end
def parent_params
params.require(:parent).permit(:email, :password, :password_confirmation)
end
Related
I'm attempting to submit a form in Rails, and it's not creating into the db. I tried placing a binding.pry in the controller action but I'm not reaching it. Can you take a look at my form below and my controller action and let me know if I'm doing anything wrong?
<form>
<%= simple_form_for #movie do |f| %>
<div class="form-group">
<%= f.input :title, placeholder: "Movie Title", input_html: { class: 'form-control' } %>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<%= f.input :year, as: :date,
start_year: Date.today.year,
end_year: Date.today.year - 100,
discard_day: true, order: [:year],
input_html: { class: 'form-control' } %>
</div>
<div class="form-group col-md-6">
<%= f.input :genre, placeholder: "Genre", input_html: { class: 'form-control' } %>
</div>
</div>
<div class="form-group">
<%= f.input :poster, placeholder: "Poster URL", input_html: { class: 'form-control' } %>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<%= f.input :director, placeholder: "Director",
input_html: { class: 'form-control' } %>
</div>
<div class="form-group col-md-6">
<%= f.input :rating, collection: 1..5, prompt: "1(bad) - 5(great)", input_html: { class: 'form-control' } %>
</div>
</div>
<div class="form-group">
<%= f.association :lists, as: :radio_buttons, input_html: { class: 'form-control' } %>
</div>
<div class="form-group">
<%= f.input :plot, as: :text, placeholder: "Plot Summary", input_html: { class: 'form-control' } %>
</div>
<div class="form-group text-center">
<%= f.button :submit, "Add Movie", class: "btn btn-primary col-md-4"
%>
</div>
<% end %>
</form>
My controller actions:
def new
#movie = Movie.new
end
def create
binding.pry
#movie = Movie.new(movie_params)
if #movie.save
redirect_to movie_path(#movie)
else
flash[:danger] = "Please try again!"
redirect_to new_movie_path
end
end
def movie_params
params.require(:movie).permit(:title, :year, :genre, :poster, :director, :plot, :list_ids)
end
Any ideas here? The form will not submit.
You need to add rating and possibly lists into your movie_params
You can also clean your create method and make it simpler:
def create
#movie = Movie.new(movie_params)
if #movie.save
redirect_to #movie
else
flash[:danger] = "Please try again!"
render 'new'
end
end
You shouldn't need to use <form> when using simple_form.
Hello rails community!
I have booking_post model that has_many reservations.
class BookingPost < ApplicationRecord
has_many :reservations, dependent: :destroy
end
All reservation belongs_to booking_post and have some validations
class Reservation < ApplicationRecord
belongs_to :booking_post
before_save { self.email = email.downcase }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }
validates :name, :email, :phone_number, :start, :end, presence: true
end
My routes are next:
resources :booking_posts do
resources :reservations, only: [:new, :create]
end
Methods:
class BookingPostsController < ApplicationController
def show
#booking_picture = #booking_post.booking_pictures.build
#booking_pictures = #booking_post.booking_pictures
#reservation = #booking_post.reservations.build
#reservations = #booking_post.reservations
end
end
class ReservationsController < ApplicationController
def new
#reservation = Reservation.new
end
def create
#booking_post = BookingPost.find(params[:booking_post_id])
#email= User.where(admin: true).first.email
#reservation = #booking_post.reservations.build(reservation_params)
if #reservation.save
#saved_reservation = #reservation
redirect_to :back
flash[:notice] = 'Reservation was successfully created.'
ReservationMailer.fresh_message(#saved_reservation, #email).deliver_now
else
redirect_to #booking_post
flash[:info] = #reservation.errors.full_messages do |m|
m
end
end
end
end
I would like to create on booking_posts/show.html.erb form_for #reservation, and render on this page errors for #reservation. When I create valid #reservation, I see on booking_posts/show.html.erb successfull flash message, but unvalid #reservation appear without any error flash messages.
form_for #reservation on booking_posts/show.html.erb:
<div class="card-action">
<%= form_for([#reservation.booking_post, #reservation], html: {multipart: true}, class: "col s12") do |f| %>
<% if #reservation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#reservation.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #reservation.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="col s6">
<%= f.label :start %>
<%= f.date_field :start, placeholder: "start time", class: "datepicker" %>
</div>
<div class="col s6">
<%= f.label :end %>
<%= f.date_field :end, placeholder: "end time", class: "datepicker" %>
</div>
<div class="col s6">
<%= f.label :reservation_time %>
<%= f.time_field :reservation_time, placeholder: "time", class: "timepicker", id: "timepicker", type: "time" %>
</div>
<div class="input-field col s6">
<%= f.label :name %>
<%= f.text_field :name, class: "validate" %>
</div>
<div class="input-field col s6">
<%= f.label :email %>
<%= f.text_field :email, class: "validate" %>
</div>
<div class="input-field col s6">
<%= f.label :phone_number %>
<%= f.text_field :phone_number, class: "validate" %>
</div>
<div class="waves-effect waves-light btn">
<%= f.submit t(:submit_reservation)%>
</div>
<% end %>
<br>
</div>
I would like render error messages for #reservation on #booking_post page
(in booking_post_path, not in new_reservation_path or anyting else). How can I do so?
Thanks for solutions
In your else block, Please update it like this
flash[:notice] = #reservation.errors.full_messages.to_sentence
redirect_to #booking_post
I have two model:
1.Personne
class Personne < ApplicationRecord
has_one :proprietaire
accepts_nested_attributes_for :proprietaire
validates :nom, :prenom, :tel, :email,
presence: true
end
2 Proprietaire
class Proprietaire < ApplicationRecord
belongs_to :personne
validates :commune_id, :quartier,
presence: true
end
the Controller is:
class PersonneController < ApplicationController
def display_proprietaires
#proprietaires = Personne.all
##proprietaires = #proprietaires.proprietaire
end
def new_proprietaire
#provinces = Province.where(:parentId => nil)
#communes = Province.where.not(:parentId => nil)
#personne = Personne.new
#personne.build_proprietaire
end
def create_proprietaire
#proprietaire = Personne.new(proprietaire_params)
#proprietaire.build_proprietaire
respond_to do |format|
if #proprietaire.save
flash[:notice] = "succes"
flash[:type] = "success"
format.html { redirect_to action: :display_proprietaires }
else
flash[:notice] = "fail"
flash[:type] = "warning"
format.html { redirect_to action: :display_proprietaires }
end
end
end
def proprietaire_params
params.require(:personne).permit(:nom, :prenom, :tel, :email, proprietaire_attributes: [:id, :commune_id, :quartier]).except(:province, :commit)
end
end
the View is:
<%= form_for #personne, :url => url_for(:controller=>'personne', :action=>'create_proprietaire' ) do |f| %>
<div class="row">
<div class="col-xs-6 col-sm-6 col-lg-6">
<div class="form-group">
<%= f.label(:nom, 'Nom : ') %>
<%= f.text_field :nom, {class: "form-control", placeholder: 'Nom'} %>
</div>
<div class="form-group">
<%= f.label(:prenom, 'Prenom : ')%>
<%= f.text_field :prenom, {class: "form-control", placeholder: "Prenom"} %>
</div>
<div class="form-group">
<%= f.label(:tel, 'Telephone : ')%>
<%= f.text_field :tel, {class: "form-control", placeholder: "Telephone"} %>
</div>
<div class="form-group">
<%= f.label(:email, 'Email : ') %>
<%= f.text_field :email, {class: "form-control", placeholder: "Email"} %>
</div>
<div class="form-group">
<%= label_tag(:province, 'Province : ') %>
<%= select_tag(:province, options_for_select(#provinces.collect{|value| [value.denomination, value.id]}), {class: "form-control", id: "province", remote: true} ) %>
</div>
<%= f.fields_for :proprietaire do |proprio| %>
<div class="form-group">
<%= proprio.label(:commune_id, 'Commune : ') %>
<%= proprio.select :commune_id, options_for_select(#communes.collect{|value| [value.denomination, value.id]}),{}, {class: "form-control", id: "commune"} %>
</div>
<div class="form-group">
<%= proprio.label :quartier, "Quartier" %>
<%= proprio.text_field :quartier, {class: "form-control", placeholder: "Quartier"} %>
</div>
<% end %>
<%= f.submit "Enregistre", {class: 'btn btn-info'} %>
<% end %>
Routes:
resources :personne do
collection do
post :create_proprietaire
get :display_proprietaires
get :new_proprietaire
end
end
I'm new in RoR, When I try to save nothing happens, I'm getting this:
Could someone helps me on this. Thank you!
You have your association set to required but it's missing.
Associations are set to required by default in rails 5 so if you want to keep one empty you need to set optional:true on your association in model
I have this form in rails, in my view new.html.erb
<%= form_for( #rent , html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Buscar', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: #rent %>
In my controller I have this
class RentsController < ApplicationController
def new
#rent = RentSearch.new
end
private
def search_params
params.require(:year).permit(:year)
end
end
In my model, had this code:
class RentSearch
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
end
With this code I get this error
undefined method `persisted?' for #
But I made some modifications and not show error, but when submit not display any error and form is empty, I don't know how can solve this.
What is the best way to create a form in rails without model access to database and passing all validations to the controller and verify.
MY SOLUTION
Thanks to #Зелёный for help.
route.rb
resources :rents, only: [:index, :new, :create]
rent.rb - model
class Rent
# Validations
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false # which means this object persisted in the database.
end
end
rents_controller.rb
class RentsController < ApplicationController
def index
#params = params
end
def new
#rent = Rent.new
end
def create
#rent = Rent.new( params['/rents'] )
if #rent.valid?
redirect_to tg_rents_path( year: params['/rents']['year'] )
else
render :action => 'new'
end
end
end
new.html.erb
<%= form_for( tg_rents_path , url: {action: "create"}, html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Search', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: #rent %>
Thanks to all!!
I'm following this tutorial to set up Devise integration with Stripe: http://www.jaredrader.com/blog/2013/12/18/a-stripe-integration
I have successfully setup Stripe as detailed and created the various controllers, models and views.
However, the forms are creating an ArgumentError in Users::Registrations#new
Here's the error code:
ArgumentError in Users::Registrations#new
Showing /home/action/workspace/mediadb/app/views/devise/registrations/new.html.erb where line #62 raised:
First argument in form cannot contain nil or be empty
The form:
<div class="panel panel-default">
<div class="panel-heading">
<% if params[:plan] == "2" %>
<h1>Sign up with premium!</h1>
</div>
<div class="panel-body">
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
<h2>Payment</h2>
<%= f.hidden_field :stripe_card_token %>
<div class="form-group">
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, name: nil, class: "form-control" %>
</div>
<div class="form-group">
<%= label_tag :card_code, "Security Code on Card (CVV)" %>
<%= text_field_tag :card_code, nil, name: nil, class: "form-control" %>
</div>
<div class="form-group">
<%= label_tag :card_month, "Card Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"}%>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"}%>
</div>
<div id="stripe_error">
<noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
</div>
<div class="form-group">
<%= f.submit "Sign up", class: "btn btn-lg btn-success" %>
</div>
<% end %>
</div>
<% else %>
<h1>Sign up for free</h1>
</div>
<div class="panel-body">
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), html: { id: "free_plan"}) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Sign up", class: "btn btn-lg btn-primary" %>
</div>
<% end %>
<% end %>
</div>
</div>
The routes.rb file:
Rails.application.routes.draw do
resources :lists
resources :publications
resources :contacts
devise_for :users, controllers: { registrations: 'users/registrations' }
devise_scope :user do
get '/sign_up', to: 'users/registrations#new', as: :sign_up
get '/sign_in', to: 'devise/sessions#new', as: :sign_in
get '/:id/edit', to: 'users/registrations#edit', as: :edit
put 'users/update_plan', :to => 'users/registrations#update_plan'
put 'users/cancel_plan', :to => 'users/registrations#cancel_plan'
end
resources :users, only: [:index, :show]
# root should always be last
root to: 'pages#home'
end
The Registration controller:
class Users::RegistrationsController < Devise::RegistrationsController
def new
unless (params[:plan] == '1' || params[:plan] == '2')
flash[:notice] = "Please select a plan to sign up."
redirect_to root_url
end
end
def update_plan
#user = current_user
#user.update_attributes(plan_id: params[:plan], email: params[:email], stripe_card_token: params[:user][:stripe_card_token])
if #user.plan_id == 2
#user.save_with_payment
redirect_to edit_user_registration_path, notice: "Updated to premium!"
else
flash[:error] = "Unable to update plan."
render :edit
end
end
def cancel_plan
#user = current_user
if #user.cancel_user_plan(params[:customer])
#user.update_attributes(stripe_customer_token: nil, plan_id: 1)
flash[:notice] = "Canceled subscription."
redirect_to edit_user_registration_path
else
flash[:error] = "There was an error canceling your subscription. Please notify us."
render :edit
end
end
private
def build_resource(*args)
super
if params[:plan]
resource.plan_id = params[:plan]
if resource.plan_id == 2
resource.save_with_payment
else
resource.save
end
end
end
def setup
plans = Plan.all
plans.each do |plan|
unless plan.id == 1
#startup_plan = plan
end
end
end
end
Any idea what's wrong?
Update Users::RegistrationsController#new as follows
def new
if (params[:plan] == '1' || params[:plan] == '2')
super
else
flash[:notice] = "Please select a plan to sign up."
redirect_to root_url
end
end