Upload Image without any gemfile Rails4 - ruby-on-rails-4

I am new in Ruby on Rails.
I trying to upload images without any gemfile. I am following http://guides.rubyonrails.org/form_helpers
Here is my books_controller.rb file:
class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
def index
#books = Book.all
end
def show
end
def new
#book = Book.new
end
def edit
end
def create
#book = Book.new(book_params)
respond_to do |format|
if #book.save
format.html { redirect_to #book, notice: 'Book was successfully created.' }
format.json { render action: 'show', status: :created, location: #book }
else
format.html { render action: 'new' }
format.json { render json: #book.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #book.update(book_params)
format.html { redirect_to #book, notice: 'Book was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #book.errors, status: :unprocessable_entity }
end
end
end
def destroy
#book.destroy
respond_to do |format|
format.html { redirect_to books_url }
format.json { head :no_content }
end
end
def upload
uploaded_io = params[:book][:image_url]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
private
def set_book
#book = Book.find(params[:id])
end
def book_params
params.require(:book).permit(:title, :description, :image_url)
end
end
and here is my form.html.erb file:
<%= form_for #book do |f| %>
<% if #book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#book.errors.count, "error") %> prohibited this book from being saved:</h2>
<ul>
<% #book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :image_url %><br>
<%= f.file_field :image_url %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Here is my schema.rb file:
ActiveRecord::Schema.define(version: 20140724173638) do
create_table "books", force: true do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.datetime "created_at"
t.datetime "updated_at"
end
end
i also create a dir(public/uploads).
But its not working.when i submit "create button" showing something like this:
TypeError: can't cast ActionDispatch::Http::UploadedFile to string: INSERT INTO "books" ("created_at", "description", "image_url", "title", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)
What's the wrong??
Thanks,
Mezbah

Related

passing id parameter to new create action - Rails 4

Could one kindly advise me how to pass an id through the actions new and create. I have tried many ways to get this right but unfortunately no success.
what i am aiming to do is, when a jobseeker (user) fills in an
application and the application fails the validations, i want a new
form to render with the advert_id passed through
i have a job advert in which i have passed the advert_id in the apply button
advert/show.html.erb
<div class="advert_summary">
<ul class="content">
<li><%= #advert.currency %><%= #advert.salarystart %> - <%= #advert.currency %><%= #advert.salaryend %> <%= #advert.category_period.name %></li>
<li>Job Type: <%= #advert.category_jobtype.name %></li>
<li>Job Ref: #<%= #advert.reference %></li>
<li>Posted: <%= #advert.created_at.strftime("%b %d, %Y") %></li>
<li>Deadline: <%= #advert.appdeadline.strftime("%b %d, %Y") %></li>
</ul>
</div>
<button><%= link_to 'Apply for job', new_form_path(advert_id: #advert.id) %></button>
i have the advert_id as a hidden field in my form (the application form for the job)
forms/_form.html.erb
<div>
<h2>Application Form</h2>
<%= simple_form_for(#form) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input_field :firstname, value: current_user.firstname, label: "firstname", placeholder: "first name" %>
<%= f.input_field :lastname, value: current_user.lastname, label: "lastname", placeholder: "last name" %>
<%= f.input_field :tel, value: current_user.tel, label: "number", placeholder: "number" %>
<%= f.input_field :email, value: current_user.email, label: "email", placeholder: "email" %>
<%= f.hidden_field :advert_id, value: params[:advert_id] %>
</div>
<div class="form-actions">
<%= f.button :submit, 'Submit Application' %>
</div>
<% end %>
</div>
in my controller forms_controller.rb i have stated the below for the create action
class FormsController < ApplicationController
respond_to :html, :xml, :json
before_action :set_form, only: [:show, :edit, :update, :destroy]
def new
#advert = Advert.find(params[:advert_id])
#user = current_user
#form = Form.new
#search = Advert.search(params[:q])
#adverts = #search.result(distinct: true)
end
def create
#user = current_user
#form = Form.new(form_params)
#advert = #form.advert
#form.user_id = current_user.id
#advert = #form.advert
if #form.save
redirect_to application_submitted_path
else
redirect_to :action => :new, :advert_id => #form.advert_id
# render :new, :advert_id => #form.advert_id
# redirect_to :action => :new, :advert_id => #form.advert_id
# redirect_to user_advert_path(#form.advert.user, #form.advert)
# respond_with(#form)
end
end
end
models
advert.rb
has_many forms
form.rb
belongs_to advert
belongs_to user (jobseeker)
user.rb (jobseeker)
has_many forms
schemas.rb
create_table "forms", force: true do |t|
t.integer "advert_id"
t.integer "user_id"
end
create_table "adverts", force: true do |t|
t.string "title"
t.text "content"
t.integer "salarystart"
t.integer "salaryend"
t.string "reference"
end
create_table "users", force: true do |t|
t.string "email",
t.string "firstname"
t.string "lastname"
end
when the jobseeker completes the application form
(forms/_form.html.erb) and the validation fails the jobseeker(user) is
directed to a new form with the advert_id passed through redirect_to
:action => :new, :advert_id => #form.advert_id
this directs me to a new form, i can see the advert_id has been passed
through the url but the form will not submit and error messages are
not being displayed.
could one kindly advise me how to successfully pass an id through the
actions new and create or where i am going wrong many thanks
Try this
forms/_form.html.erb
<div>
<h2>Application Form</h2>
<%= simple_form_for(#form) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input_field :firstname, value: current_user.firstname, label: "firstname", placeholder: "first name" %>
<%= f.input_field :lastname, value: current_user.lastname, label: "lastname", placeholder: "last name" %>
<%= f.input_field :tel, value: current_user.tel, label: "number", placeholder: "number" %>
<%= f.input_field :email, value: current_user.email, label: "email", placeholder: "email" %>
<%= f.hidden_field :advert_id, value: #advert_id %>
</div>
<div class="form-actions">
<%= f.button :submit, 'Submit Application' %>
</div>
<% end %>
</div>
class FormsController < ApplicationController
respond_to :html, :xml, :json
before_action :set_form, only: [:show, :edit, :update, :destroy]
def new
#advert = Advert.find(params[:advert_id])
#user = current_user
#form = Form.new
#search = Advert.search(params[:q])
#advert_id = params[:advert_id]
#adverts = #search.result(distinct: true)
end
def create
#user = current_user
#form = Form.new(form_params)
#advert = #form.advert
#form.user_id = current_user.id
#advert_id = params[:form][:advert_id]
#advert = #form.advert
respond_to do |format|
if #form.save
format.html { redirect_to #form, notice: 'Created.' }
format.json { render :show, status: :created, location: #form }
else
format.html { render :new }
format.json { render json: #form.errors, status: :unprocessable_entity }
end
end
end
end

undefined method `first_name' for nil:NilClass error

I am trying to make a relationship between a user and a shipment model. Am using [devise][1] for generating users everything gone good but now am stopped at this. I am getting This error:
undefined method `first_name' for nil:NilClass
My models
Shipment.rb
class Shipment < ActiveRecord::Base
belongs_to :user
end
User.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
My controllers
Shipments_Controller.rb
class ShipmentsController < ApplicationController
before_action :set_shipment, only: [:show, :edit, :update, :destroy]
# GET /shipments
# GET /shipments.json
def index
#shipments = Shipment.all
end
# GET /shipments/1
# GET /shipments/1.json
def show
end
# GET /shipments/new
def new
#shipment = Shipment.new
end
# GET /shipments/1/edit
def edit
end
# POST /shipments
# POST /shipments.json
def create
#shipment = Shipment.new(shipment_params)
respond_to do |format|
if #shipment.save
format.html { redirect_to #shipment, notice: 'Shipment was successfully created.' }
format.json { render :show, status: :created, location: #shipment }
else
format.html { render :new }
format.json { render json: #shipment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /shipments/1
# PATCH/PUT /shipments/1.json
def update
respond_to do |format|
if #shipment.update(shipment_params)
format.html { redirect_to #shipment, notice: 'Shipment was successfully updated.' }
format.json { render :show, status: :ok, location: #shipment }
else
format.html { render :edit }
format.json { render json: #shipment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /shipments/1
# DELETE /shipments/1.json
def destroy
#shipment.destroy
respond_to do |format|
format.html { redirect_to shipments_url, notice: 'Shipment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_shipment
#shipment = Shipment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def shipment_params
params.require(:shipment).permit(:user_id, :description, :from, :to, :date, :pay)
end
end
My db Migration files are:
devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :first_name
t.string :last_name
t.string :city_name
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
add_user_id_to_shipment.rb
class AddUserIdToShipments < ActiveRecord::Migration
def change
add_column :shipments, :user_id, :integer
add_index :shipments, :user_id
remove_column :shipments, :name
end
end
My Shipment Views files:
_form.html.erb
<%= simple_form_for(#shipment, html: {class: "form-horizontal"}) do |f| %>
<% if #shipment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#shipment.errors.count, "error") %> prohibited this shipment from being saved:</h2>
<ul>
<% #shipment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.input :user_id %>
<%= f.input :description %>
<div class="field">
<%= f.label :ship_from %><br>
<%= f.select :from, ['New York']%>
</div>
<div class="field">
<%= f.label :ship_to %><br>
<%= f.select :to, [ 'New york', 'Orlanda' ] %>
</div>
<%= f.input :date %>
<%= f.input :pay %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Index.html.erb
<div class="page-header">
<h1>Listing Shipments</h1>
</div>
<%= link_to "Post a new Shipment", new_shipment_path, class: "btn btn-success" %>
<% #shipments.each do |shipment| %>
<div class="shipment">
<h3><strong><%= shipment.user.first_name %></strong></h3>
<h5><strong>DESCRIPTION: </strong><%= shipment.description %></h5>
<div class="meta">
<%= link_to time_ago_in_words(shipment.created_at) + " ago" %> |
<%= link_to "show", shipment %>
<span class="admin">
| <%= link_to "Edit", edit_shipment_path(shipment) %> |
<%= link_to "Delete", shipment, method: :delete, data: { confirm: "Are you sure?"} %>
</span>
</div>
</div>
<% end %>
Show.html.erb
<%= notice %>
<p>
<strong>Name:</strong>
<%= #shipment.user.first_name %>
</p>
<p>
<strong>Shipment Description:</strong>
<%= #shipment.description %>
</p>
<p>
<strong>Shipment From:</strong>
<%= #shipment.from %>
</p>
<p>
<strong>Ship To:</strong>
<%= #shipment.to %>
</p>
<p>
<strong>Shipment Date:</strong>
<%= #shipment.date %>
</p>
<p>
<strong>Pay:</strong>
<%= #shipment.pay %>
</p>
<%= link_to 'Edit', edit_shipment_path(#shipment) %> |
<%= link_to 'Back', shipments_path %>
My command line show this log:
Started GET "/" for ::1 at 2015-07-28 16:07:24 +0530
Processing by ShipmentsController#index as HTML
Shipment Load (0.0ms) SELECT "shipments".* FROM "shipments"
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT
1 [["id", 1]]
Rendered shipments/index.html.erb within layouts/application (0.0ms)
Completed 500 Internal Server Error in 16ms (ActiveRecord: 0.0ms)
ActionView::Template::Error (undefined method `first_name' for nil:NilClass):
6:
7: <% #shipments.each do |shipment| %>
8: <div class="shipment">
9: <h3><strong><%= shipment.user.first_name %></strong></h3>
10: <h5><strong>DESCRIPTION: </strong><%= shipment.description %></h5>
11: <div class="meta">
12: <%= link_to time_ago_in_words(shipment.created_at) + " ago" %> |
app/views/shipments/index.html.erb:9:in `block in _app_views_shipments_index_h
tml_erb__634505161_51269712'
app/views/shipments/index.html.erb:7:in `_app_views_shipments_index_html_erb__
634505161_51269712'
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.2.3
/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.2.3
/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.2.3
/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
(0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.2.3
/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within
rescues/layout (31.2ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/_markup.html.erb (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inline
d_string (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_s
tring (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/console.js.erb within layouts/javascript (31.2ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/main.js.erb within layouts/javascript (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.0ms)
Rendered C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.2.
1/lib/web_console/templates/index.html.erb (78.0ms)
It looks like a particular shipment has no user associated to it. For a quick fix, try the below code
<h3><strong><%= shipment.try(:user).try(:first_name) %></strong></h3>

Forms, nested resources and routing errors Rails 4

Rails newbie here. I have created a basic website that tracks events during a shift. I have created the models and nested them. However, I do not understand the connections completely.
When I create the nested event from a form linked to a shift I get the following error:
No route matches [POST] "/shifts/events" on url http://localhost:3000/shifts//events
should be http://localhost:3000/shifts/3/events/1 I think
_form.html.erb
<%= form_for shift_events_path(#shift) do |f| %>
<% if #event.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#event.errors.count, "error") %> prohibited </h2>
<ul>
<% #event.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :time_s %><br>
<%= f.time_select :time_s %>
</div>
<div class="field">
<%= f.label :time_f %><br>
<%= f.time_select :time_f %>
</div>
<div class="field">
<%= f.label :odometre %><br>
<%= f.number_field :odometre %>
</div>
<div class="field">
<%= f.label :location %><br>
<%= f.text_field :location %>
</div>
<div class="field">
<%= f.label :activity %><br>
<%= f.text_field :activity %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description, rows: 4 %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
roots.rb
resources :shifts do
resources :events#,
end
events_controller.eb
class EventsController < ApplicationController
before_filter :get_shift
before_action :set_event, only: [:show, :edit, :update, :destroy]
# GET /events
# GET /events.json
def index
#events = #shift.events
end
# GET /events/1
# GET /events/1.json
def show
end
# GET /events/new
def new
#event = #shift.events.build
end
# GET /events/1/edit
def edit
end
# POST /events
# POST /events.json
def create
#event = #shift.events.build(event_params)
respond_to do |format|
if #event.save
format.html { redirect_to shift_event_path, notice:
'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: #event }
else
format.html { render action: 'new' }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /events/1
# PATCH/PUT /events/1.json
def update
respond_to do |format|
if #event.update(event_params)
format.html { redirect_to shift_event_path, notice:
'Event was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
end
end
# DELETE /events/1
# DELETE /events/1.json
def destroy
#event.destroy
respond_to do |format|
format.html { redirect_to shift_event_path }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event
#event = #shift.events.find(params[:id])
end
def get_shift
#shift = Shift.find(params[:shift_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def event_params
params.require(:event).permit(:time_s, :time_f, :odometre,
:location, :activity, :shift_id)
end
end
routes
shift_events_path GET /shifts/:shift_id/events(.:format) events#index
POST /shifts/:shift_id/events(.:format) events#create
new_shift_event_path GET /shifts/:shift_id/events/new(.:format) events#new
edit_shift_event_path GET /shifts/:shift_id/events/:id/edit(.:format) events#edit
shift_event_path GET /shifts/:shift_id/events/:id(.:format) events#show
PATCH /shifts/:shift_id/events/:id(.:format) events#update
PUT /shifts/:shift_id/events/:id(.:format) events#update
DELETE /shifts/:shift_id/events/:id(.:format) events#destroy
shifts_path GET /shifts(.:format) shifts#index
POST /shifts(.:format) shifts#create
new_shift_path GET /shifts/new(.:format) shifts#new
edit_shift_path GET /shifts/:id/edit(.:format) shifts#edit
shift_path GET /shifts/:id(.:format) shifts#show
PATCH /shifts/:id(.:format) shifts#update
PUT /shifts/:id(.:format) shifts#update
DELETE /shifts/:id(.:format) shifts#destroy
root_path GET / shifts#index
I figure the form first line is wrong but I don't know what to change it to. Secondly, I think some the connections in the events controller are wrong. Any help would be appreciated.
Try this:
<%= form_for [#shift, #event] do |f| %>
Now you will post a particular event for a particular shift.

Rails 4 how to create and listing in the same page

I have a model product and I want to create and then list under the text_field
in my controller
class ProductController < ApplicationController
def buy
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully added.'}
else
format.html { redirect_to #product, notice: 'Failed to added.'}
end
end
end
private
def product_params
params.permit(:name, :description)
end
end
and view
<%= simple_form_for #product, :url => { :controller => 'product', :action => 'buy'} do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.button :label => 'BUY', :class => 'btn add-product btn-primary' %>
<% end %>
and I try to list in the same view
<% #products.each do |product| %>
<%= product.name %>
<%= product.description %>
and script
<script>
$('.add-product').click(function(){
$('.product').clone().first().appendTo('.container');
})
I'm not sure the code can be run or not
Cuz I got a problem with
undefined method `model_name' for NilClass:Class
in this <%= simple_form_for #product, :url => { :controller => 'product', :action => 'buy'} do |f| %>
my question is like Append form partial in the new view of the same model in rails
but I can't use %input{:name => "model[][name]"} to be my input
Can help me how to fix my code
thanks~
#pruduct is a typo. make it #product. does that fix it?
based on comments.
class ProductController < ApplicationController
def index
#products = Product.all
#product = Produc.new
end
def buy
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to products_path, notice: 'Product was successfully added.'}
else
format.html do
#products = Product.all
flash.now[:error] = 'Failed to add product'
render action: 'index'
end
end
end
end
end
Had to change the redirect on failed since if it didn't save you won't have an ID, and won't be able to redirect to it.
Then in your index.html.erb view
<%= simple_form_for #product, :url => { :controller => 'product', :action => 'buy'} do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.button :label => 'BUY', :class => 'btn add-product btn-primary' %>
<% end %>
<% #products.each do |product| %>
<%= product.name %>
<%= product.description %>
<% end %>
I think that should do what you are asking.

Ruby on Rails Getting name can't be blank error when trying to add new user

I am a Ruby on Rails newbie, and am trying to put into practice some of the tutorials I have been following.
I am currently trying to get a basic user signup working.
When the signup form is completed and submitted, the Firstname and Lastname fields are blanked out and I get two error messages (I also get a failing error when running the cucumber tests):
Firstname can't be blank
Lastname can't be blank
I think I have missed something fairly obvious with the authentication code, but can't spot what I have missed.
All my code is on my github account
Controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
#users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: #user }
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:firstname, :middlename, :lastname, :email, :password, :password_confirmation)
end
end
Model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :firstname, :lastname, :middlename
validates :firstname, :presence =>true
validates :lastname, :presence=>true
validates :email, :presence=>true, :uniqueness => { :case_sensitive => false }
before_validation :downcase_email
def name
[firstname, middlename, lastname].compact.join(' ')
end
private
def downcase_email
self.email = self.email.downcase if self.email.present?
end
end
Views User
new.erb.rb
<h1>New user</h1>
<%= render 'form' %>
<%= link_to 'Back', users_path %>
_form.rb
<%= form_for(#user) do |f| %>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :firstname %><br />
<%= f.text_field :firstname %>
</div>
<div class="field">
<%= f.label :lastname %><br />
<%= f.text_field :lastname %>
</div>
<div class="field">
<%= f.label :middlename %><br />
<%= f.text_field :middlename %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Since it looks like you're using devise, you can try running rails generate devise:views. This will generate all of the correct views for everything devise does. You might want to save the forms that you already have in case Devise tries to override them, though.