Can't generate a form with form helpers - ruby

I'm trying to generate a form with an html.erb file, that looks something like this:
<form class="edit-booking" method="post" action="/users/<%= current_user.id %>/accounts/1/bookings/new" data-remote="true">
<header><h1>Edit booking</h1></header>
<input class="booking-name" name="booking[name]" placeholder="Name of the user" type="text" />
<fieldset class="booking-list">
<h2>Booking details</h2>
<ul>
<li>
<input name="booking[name]" type="text" value="Unit name" disabled/>
<input name="booking[check_in]" type="date" value="" />
<input name="booking[check_out]" type="date" value="" />
</li>
</ul>
</fieldset>
<input name="submit" type="submit" value="Save" />
</form>
an I have this ruby code:
<%= form_for [current_user] do |f| %>
<header>
<h1>Edit booking</h1>
</header>
<%= field_set_tag 'Booking details' do %>
<%= f.fields_for :bookings do |booking_form| %>
<%= booking_form.text_field :name, placeholder: "Name" %>
<%= booking_form.text_field :check_in, placeholder: "Check-in" %>
<%= booking_form.text_field :check_out, placeholder: "Check-out" %>
<% end %>
<% end %>
<%= f.submit "Save" %>
<% end %>
But what happens is, it doesn't render anything on the browser even though in the chrome dev tool it shows a form tag.
EDIT:
The html generated is as following:
<form accept-charset="UTF-8" action="/users/1/accounts/1" class="edit_account" id="edit_account_1" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="patch"><input name="authenticity_token" type="hidden" value="fzA+hkk3o+itJOI0UDj9F01DuI+A5+zgQ1EVGlwrPww="></div>
<header>
<h1>Edit booking</h1>
</header>
<fieldset><legend>Booking details</legend>
<input id="account_bookings_name" name="account[bookings][name]" placeholder="Name" type="text">
<input id="account_bookings_check_in" name="account[bookings][check_in]" placeholder="Check-in" type="text">
<input id="account_bookings_check_out" name="account[bookings][check_out]" placeholder="Check-out" type="text">
</fieldset>
<input name="commit" type="submit" value="Save">
</form>
My Account model:
class Account < ActiveRecord::Base
belongs_to :user
has_many :products
has_many :bookings
accepts_nested_attributes_for :bookings
accepts_nested_attributes_for :products
end

In your model add:
#Account model
accepts_nested_attributes_for :bookings
Also, should your current_user be an account?

Related

How to add show/hide action in rails forms only in the view template

I'm new to rails and using to devise for authentication, what i want to accomplish is user privacy.
Meaning in edit form i want to add a toggle switch action for example 'Email field' to give the user the ability to show/hide fields in his profile but the form still displayed in the edit view.
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<div class="container mt-5">
<div class="row">
<div class="col-sm-3">
<!-- Left menu links -->
<ul class="nav-item pl-0">
<h4 class="nav-link disabled mb-0 text-dark font-weight-bold">Settings</h4>
<%= link_to 'Personal information', "/users/edit", class: "nav-link text-dark font-weight-bold" %>
<%= link_to 'Account settings', "/account/settings", class: "nav-link text-dark font-weight-bold" %>
<%= link_to 'Password settings', "/account/passwords", class: "nav-link text-dark font-weight-bold" %>
<%= link_to 'Security', "/account/security", class: "nav-link text-dark font-weight-bold" %>
</ul>
</div>
<!-- Right from inputs -->
<div class="col-sm-9 shadow-sm border border-dark p-3 mb-5 mx-3 mx-sm-0 mx-lg-0 mx-xl-0 bg-white rounded">
<div class="form-inline form-group">
<div class="col-sm-2">
<label class="text-dark font-weight-bold justify-content-start">First name:</label>
</div>
<div class="col-sm-4">
<%= f.input :first_name, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "First name"} %>
</div>
</div>
<div class="form-inline form-group">
<div class="col-sm-2">
<label class="text-dark font-weight-bold justify-content-start">Last name:</label>
</div>
<div class="col-sm-4">
<%= f.input :last_name, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Last name"} %>
</div>
</div>
<div class="dropdown-divider my-4"></div>
<label class="text-dark font-weight-bold px-3 mb-4">Biography</label>
<div class="form-inline form-group">
<div class="col-sm-2">
<label class="text-dark font-weight-bold justify-content-start">About:</label>
</div>
<div class="col-sm-10">
<%= f.input :about, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Write in few lines something about yourself and what you are passionate about"} %>
</div>
</div>
<div class="dropdown-divider mt-5 mb-4"></div>
<label class="text-dark font-weight-bold px-3 mb-4">Career</label>
<div class="form-inline form-group">
<div class="col-sm-2">
<label class="text-dark font-weight-bold justify-content-start">Company:</label>
</div>
<div class="col-sm-10">
<%= f.input :company, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Where do you work?"} %>
</div>
</div>
<div class="form-inline form-group">
<div class="col-sm-2">
<label class="text-dark font-weight-bold justify-content-start">Job title:</label>
</div>
<div class="col-sm-10">
<%= f.input :job_title, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Current working position?"} %>
</div>
</div>
<div class="form-inline form-group">
<div class="col-sm-2">
<label class="text-dark font-weight-bold justify-content-start">School / University:</label>
</div>
<div class="col-sm-10">
<%= f.input :school, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Name of school or university"} %>
</div>
</div>
<!-- Right update button -->
<div class="form-inline justify-content-end py-2 px-3">
<div class="col-sm-2">
<%= f.button :submit, "Update", class: "btn btn-primary btn-sm btn-block" %>
</div>
</div>
</div>
</div>
</div>
</div>
<% end %>
i made a custom devise registration controller
app/controllers/registations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
resource_updated = update_resource(resource, account_update_params)
yield resource if block_given?
if resource_updated
set_flash_message_for_update(resource, prev_unconfirmed_email)
bypass_sign_in resource, scope: resource_name if sign_in_after_change_password?
respond_with resource, location: after_update_path_for(resource)
else
clean_up_passwords resource
set_minimum_password_length
session[:return_to] ||= request.referer
redirect_to session.delete(:return_to), alert: resource.errors.full_messages[0]
end
end
def settings
#user = current_user
if #user
render :settings
else
render file: 'public/404', status: 404, formats: [:html]
end
end
def passwords
#user = current_user
if #user
render :passwords
else
render file: 'public/404', status: 404, formats: [:html]
end
end
def security
#user = current_user
if #user
render :security
else
render file: 'public/404', status: 404, formats: [:html]
end
end
end
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!
def show
#user = current_user
end
end
routes.rb
Rails.application.routes.draw do
get 'users/show'
root 'pages#home'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
devise_for :users, controllers: { registrations: "registrations" }
resources :user, only: [:show]
devise_scope :user do
get 'accounts/settings', to: 'registrations#settings', as: :settings
get 'accounts/passwords', to: 'registrations#passwords', as: :passwords
get 'accounts/security', to: 'registrations#security', as: :security
end
end
You'll want to do 3 things:
Add a button with an onclick handler that allows the user to click on it to hide/show the field
Add an ID to the div you are using to show the attribute
Create a javascript function to show/hide that div
So add the button outside the div you are hiding and include the onclick
<%= button_tag "Hide/Show", :onclick => "hideInput()" %>
Then add the ID to the div you are hiding. In your case, do something like this. You can use any ID you want. Mine is just an example.
<div id="emailDisplayed" class="text-dark"> <%= #user.email %> </div>
Then you want to add the hideInput function in your javascript file. Preferably in assets/javascripts/[file_name]
function hideInput() {
var emailDiv = document.getElementById("emailDisplayed");
emailDiv.style.display === "block" ? emailDiv.style.display = 'none' : emailDiv.style.display = 'block';
}
Now when the user clicks on the button, it will hide/show your div that contains the user email.

Ruby on Rails : Paperclip::AdapterRegistry::NoHandlerError in UsersController#update

What am I doing wrong?
Paperclip::AdapterRegistry::NoHandlerError in UsersController#update
No handler found for "S__28434447.jpg"
#user = User.find(params[:id])
if #user.update(user_params)
flash[:notice] = "edit success"
redirect_to("/users/#{#user.id}")
end
users_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user
def edit
#user = User.find_by(id: params[:id])
end
def update
#user = User.find(params[:id])
if #user.update(user_params)
flash[:notice] = "edit success"
redirect_to("/users/#{#user.id}")
end
end
private
def user_params
params.require(:user).permit(:avatar, :name, :email, :phone_number, :description)
end
end
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"hRL4l1uZtBP8N9uQZeImLSOyn/u10Qc7zXiJBkFvVJvzO7bS6DxGVpIozEu0fjWRAZU1YGsfMgj6bwNT1P1FFg==",
"user"=>{"name"=>"admin", "avatar"=>"S__28434447.jpg", "email"=>"admin#gmail.com", "phone_number"=>"", "description"=>""},
"id"=>"1"}
edit.html.erb
<%= form_tag("/users/#{#user.id}/update", html:{multipart: true}) do %>
<div class="form-group">
<p>*ユーザー名</p>
<input name="user[name]" value="<%= #user.name %>" class="form-control">
</div>
<div class="form-group">
<p>プロフィール画像</p>
<input name=user[avatar] type="file" value="<%= #user.avatar %>" class="form-control">
</div>
<div class="form-group">
<p>*メールアドレス</p>
<input name=user[email] value="<%= #user.email %>" class="form-control">
</div>
<div class="form-group">
<p>電話番号</p>
<input name=user[phone_number] value="<%= #user.phone_number %>" class="form-control">
</div>
<div class="form-group">
<p>自己紹介</p>
<input name=user[description] value="<%= #user.description %>" class="form-control">
</div>
<div class="actions">
<input type="submit" value="保存" class="btn btn-primary">
</div>
<% end %>
I use gem file
gem 'paperclip'
gem 'aws-sdk', '~> 2.3'
I use rails 5
I do not know where wrong.
So please tell me about the improvement points.
Do this
Remove this line <input name=user[avatar] type="file" value="<%= #user.avatar %>">
And Add this line <%= file_field_tag :avatar %> in place of prev code.
Reference: document
Happy Coding
Cheers!

Redirect to same page using Rails 3

I need after user's action complete the page should exactly remain same using Rails 3.I am explaining my code and code flow below.
home.html.erb:
<div class="col-md-6" style="float:none; margin:auto;">
<%= form_for :sdf ,:url => {:action => "scan_report" },:html => {:id =>"form-id" } ,remote: true do |f| %>
<% if params[:receipt_no] %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control", :value => params[:receipt_no],:id => "scan-field",:onfocus => ("$('#rcd_btn').submit()") %>
</div>
<% else %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control",placeholder:"Receipt No. scan" %>
</div>
<% end %>
<%= f.submit "Submit",:id => "rcd_btn",:style => "display:none;" %>
<% end %>
<div class="clearfix"></div>
</div>
<div class="block block-themed" style="display:none" id="whole-div6" >
<div class="block-title">
<div class="block-options">
<i class="fa fa-arrow-down"></i>
</div>
<h4>Wood Slip</h4>
</div>
<div id="wood-puri">
</div>
</div>
From the above form when user will put the receipt no,lets say 150325006/1 and pressing enter key the below page will display.
_wood.html.erb:
<div class="block-content" style="display:none;">
<div class="timeline-container">
<div class="input-group bmargindiv1 col-md-6 pull-left"><span class="input-group-addon text-left"><div class="leftsidetextwidth">Receipt No :</div></span>
<input type="text" class="form-control" value= "<%= #sdf.Receipt_No %>">
</div>
<div class="input-group bmargindiv1 col-md-6 pull-left"><span class="input-group-addon text-left"><div class="leftsidetextwidth">Date & Time :</div></span>
<input type="text" class="form-control" value= "<%= #sdf.Created_On %>">
</div>
<div class="input-group bmargindiv1 col-md-6 pull-left"><span class="input-group-addon text-left"><div class="leftsidetextwidth">Deceased Name :</div></span>
<input type="text" class="form-control" value= "<%= #hcsy.Deceased_Name %>">
</div>
<div class="input-group bmargindiv1 col-md-6 pull-left"> <span class="input-group-addon text-left"><div class="leftsidetextwidth">Donor Name :</div></span>
<input type="text" class="form-control" value= "<%= #sdf.Doner_Name %>">
</div>
<div class="input-group bmargindiv1 col-md-12 pull-left"> <span class="input-group-addon text-left"><div class="leftsidetextwidth">Amount :</div></span>
<input type="text" class="form-control" value= "<%= #woods.Amount %>">
</div>
<div class="clearfix"></div>
</div>
<div class="block block-themed themed-asphalt">
<div class="block-title"><h5>Office Use</h5></div>
<div class="block-content full">
<%= form_for :vendor,:url => {:action =>"payment" } do |f| %>
<div class="totalaligndiv">
<div class="input-group bmargindiv1 col-md-6" style="margin:auto; float:none;"><span class="input-group-addon text-left"><div class="leftsidetextwidth">Select Vendor :</div></span>
<%= f.select(:v_name,options_for_select(Vendor.where(s_catagory: "Woods").pluck(:v_name),selected: "Select vender name"),{},{:class => "form-control",:prompt => 'Selected Vendor'}) %>
</div>
<div class="totalaligndiv">
<%= f.hidden_field :receipt_no, :value => #sdf.Receipt_No %>
</div>
<div class="totalaligndiv">
<%= f.hidden_field :amount,:value => #woods.Amount %>
</div>
<div class="totalaligndiv">
<%= f.hidden_field :date,:value =>#sdf.Created_On %>
</div>
<div class="clearfix"></div>
<div class="tbpaddingdiv1 text-center">
<%= f.submit "Add to Payment",:class => "btn btn-success" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
</div>
</div>
</div>
From the above page user will select one vendor name when user will click on submit button the db operation will happen and user will stay on the same page which was displaying before(i.e-user will stay on that _woods.html.erb page also after submit) submit button pressed and the "Add to Payment" vanishes till the next receipt no scan.My controller file is given below.
homes_controller.rb:
class HomesController < ApplicationController
def home
#sdf=TSdf.new
respond_to do |format|
format.html
format.js
end
end
def scan_report
if #sdf=TSdf.find_by_Receipt_No(params[:sdf][:Receipt_No])
#hcsy=THcsy.find_by_Sdp_Id(#sdf.Sdp_Id)
#hcsy_deatils=THcsyDetails.find_by_HCSY_ID(#hcsy.id)
#woods=THcsyFundTypeMaster.find_by_Fund_Type_Code(1)
#burn=THcsyFundTypeMaster.find_by_Fund_Type_Code(2)
#good=THcsyFundTypeMaster.find_by_Fund_Type_Code(3)
#swd=THcsyFundTypeMaster.find_by_Fund_Type_Code(5)
#photo=THcsyFundTypeMaster.find_by_Fund_Type_Code(6)
#vendor=Vendor.new
flash[:notice]=" number matched"
else
splitted = params[:sdf][:Receipt_No].split('/')
receipt = splitted[0]
table_id = splitted[1]
#sdfs=TSdf.find_by_Receipt_No(receipt)
if #sdfs
#hcsys=THcsy.find_by_Sdp_Id(#sdfs.Sdp_Id)
#fund_details=THcsyFundTypeMaster.find_by_Fund_Type_Code(table_id)
else
flash[:notice]="Scan number not found"
end
end
end
def payment
#adds=THcsyFundTypeMaster.find_by_Amount(params[:vendor][:amount])
#vendor=PaymentVendor.create(:Receipt_No => params[:vendor][:receipt_no],:c_date => Date.today.to_time_in_current_zone,:v_date => params[:vendor][:date],:v_amount => params[:vendor][:amount],:v_catagory => #adds.Fund_Type_Name,:v_name => params[:vendor][:v_name],:v_status => "No" )
if #vendor
flash[:notice]="Vendor added the payment"
flash[:color]="valid"
redirect_to :action => "home"
else
flash[:alert]="vendor could not added the payment"
flash[:color]="invalid"
render 'home'
end
end
end
scan_report.js.erb:
<% if #fund_details.Fund_Type_Name=="Woods" %>
$("#whole-div6").css("display", "block");
$("#wood-puri").html("<%= escape_javascript (render 'woods' ) %>");
$("#wood-puri").slideDown(350);
<% end %>
Here inside payment action now i am redirecting home page .But i need user will stay on that rendered _wood.html.erb: page after click on add to payment button.Please help me.
Did you tried :back? i.e. in controller
respond_to do |format|
format.html { redirect_to :back }
end
It will redirect to the page from where request was arrived.

Template missing error in Rails 3

Hi i am facing the following error while trying to create a user using Rails 3.
Error:
Template is missing
Missing template admins/index, application/index with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "C:/Site/swargadwar_admin/app/views"
Please check my below code and try to help me to resolve this error.
views/homes/index.html
<div class="container">
<div style="text-align:center;"><img src="/assets/admin.png" style="width:100px; height:120px; " /></div>
<div class="text-div" style="text-align:center;">Swargadwar, Puri Municipality,govt of odisha</div>
<section>
<div id="container_demo" >
<!-- hidden anchor to stop jump http://www.css3create.com/Astuce-Empecher-le-scroll-avec-l-utilisation-de-target#wrap4 -->
<a class="hiddenanchor" id="toregister"></a>
<a class="hiddenanchor" id="tologin"></a>
<div id="wrapper">
<div id="login" class="animate form">
<form action="mysuperscript.php" autocomplete="on">
<h1>Log in</h1>
<p>
<label for="username" class="uname" data-icon="u" > Your email or username </label>
<input id="username" name="username" required type="text" placeholder="myusername or mymail#mail.com"/>
</p>
<p>
<label for="password" class="youpasswd" data-icon="p"> Your password </label>
<input id="password" name="password" required type="password" placeholder="eg. X8df!90EO" />
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />
<label for="loginkeeping">Keep me logged in</label>
</p>
<p class="login button">
<input type="submit" value="Login" />
</p>
<p class="change_link">
Not a member yet ?
Join us
</p>
</form>
</div>
<div id="register" class="animate form">
<%= form_for :admins,:url => {:action => 'create_registration',:controller => "admins" } do |f| %>
<h1> Sign up </h1>
<p>
<label for="usernamesignup" class="uname" data-icon="u">Your username</label>
<%= f.text_field :user_name,placeholder:"mysuperusername690",:id => "usernamesignup" %>
</p>
<p>
<label for="emailsignup" class="youmail" data-icon="e" > Your email</label>
<%= f.email_field :email,placeholder:"mysupermail#mail.com",:id => "emailsignup" %>
</p>
<p>
<label for="passwordsignup" class="youpasswd" data-icon="p">Your password </label>
<%= f.password_field :password,placeholder:"eg. X8df!90EO",:id => "passwordsignup" %>
</p>
<p>
<label for="passwordsignup_confirm" class="youpasswd" data-icon="p">Please confirm your password </label>
<%= f.password_field :password_confirmation,placeholder:"eg. X8df!90EO",:id => "passwordsignup" %>
</p>
<p>
<label for="usernamesignup" class="uname" data-icon="u">Add Image</label>
<%= f.file_field :picture %>
</p>
<p class="signin button">
<%= f.submit "Sign Up"%>
</p>
<p class="change_link">
Already a member ?
Go and log in
</p>
<% end %>
</div>
<div class="error-div">
<% if #admin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#admin.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #admin.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
</div>
</div>
</div>
</section>
</div>
controller/admins_controller.rb
class AdminsController < ApplicationController
def create_registration
#admin=Admin.new(params[:admin])
if #admin.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => "index" , :controller => "homes"
else
flash[:alert]="User could not created"
flash[:color]="invalid"
render 'index', :controller => "homes"
end
end
end
routes.rb
SwargadwarAdmin::Application.routes.draw do
root :to => "homes#index"
get "homes/index" => "homes#index"
post "admins/create_registration" => "admins#create_registration"
end
controller/homes_controller.rb
class HomesController < ApplicationController
def index
#admin=Admin.new
end
end
Actually i was trying by insert wrong data for checking validation and got this error at this line "render 'index',:controller => 'homes'".Please help me.

submit action doesnt work in Rails 4

when I submitted the form, the new data don't save in database and as a result I can not see them, but when I make a new data like welcome= Welcome.new and welcome.title="your are" by rails console they work and I can only see things that I have made in console not by application. It seems submit bottom doesnt save any data.
new.html.erb
<h1> Submite </h1>
<form action="new" method="post" class="form-horizontal" role ="form">
<div class="form-group">
<label for"kind"> kind </label>
<input type="string" id="kind" name="kind" class="form-control">
</div>
<br>
<div class="form-group">
<label for"title"> title </label>
<input type="string" id="title" name="title" class="form-control">
</div>
<br>
<div class="form-group">
<label for"text">"text </label>
<input type="text" id="text" name="text" class="form-control">
<br>
</div>
<br>
</div>
<input type="submit" value="Submit" class="btn btn-primary">
List
</div>
index.html.erb
<% #welcomes.each do |welcome| %>
<li><%= welcome.title %> </li>
<% end %>
welcomes_controller
def index
#welcomes = Welcome.all
end
def new
#welcome = Welcome.new
end
def create
#welcome = Welcome.new(user_params)
if #welcome.save
flash.keep[:notice]="Successfuly created"
render :index
else
render :new
# format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
private
def user_params
params.require(:welcome).permit(:kind, :title, :text)
end
Your form is not submitting to the right route. Use form builder instead:
<%= form_for #welcome do |f| %>
<%= f.label :kind %>
<%= f.text_field :kind %>
<%= f.submit %>
<% end %>
This will put right route for form submission into your HTML

Resources