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>
Related
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
I would like with Rails4 to assign the current_user.email to a comment.
This comment is assign to a book.
[Page book][1] [1]: http://i.stack.imgur.com/2mEoG.png
I succeed to assign the current_user.email to a comment
but when i try to change the current_user with an other account, all the email of the comments change also. And i don't want that!
How can i resolve the problem?
Here some files of my app:
CommentsController:
class CommentsController < ApplicationController
def create
#book = Book.find(params[:book_id])
#comment = #book.comments.new(comment_params)
if #comment.save
redirect_to #comment.book, notice: I18n.t('books.comment')
else
render text: 'Error!'
end
end
private
def comment_params
params.require(:comment).permit(:message)
end
end
view:
<% if comment.message != nil %>
<li><strong><%= current_user.email %></strong></li>
<p><%= comment.message %></p>
<% end %>
form_for:
<%= form_for [#book, #comment] do |f| %>
<%= f.hidden_field :book_id %>
<%= f.text_area :message, :placeholder => "Message" %>
<br />
<%= f.submit %>
<% end %>
Table Comments:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :message
t.string :username
t.integer :book_id
t.integer :reader_id
t.integer :user_id
t.timestamps
end
end
end
Table Readers:
class CreateReaders < ActiveRecord::Migration
def change
create_table :readers do |t|
t.string :name
t.string :email
t.timestamps
end
end
end
Table Books:
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :title
t.string :author
t.string :synopsis
t.timestamps
end
end
end
Well, if you want have assigned current user to comment you can place a hidden field to save users id (make sure you have configured associations in models):
form_for:
<%= form_for [#book, #comment] do |f| %>
...
<%= f.hidden_field :user_id, value: current_user.id %>
...
<% end %>
Update comment_params in controller:
private
def comment_params
params.require(:comment).permit(:message, :user_id)
end
and then, in view:
<% if comment.message != nil %>
<li>
<strong>
<%= comment.user.email %>
</strong>
</li>
<p><%= comment.message %></p>
<% end %>
That's it. If you need use reader model instead of user - you can do it in the same way..
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
I used associations in the models whenever I am applying associations I am getting problem ,I am new to ruby as well as rails.I am using Rails4,Eclipse,Windows Xp(sp3) and mysql5.6 ,I am getting the above error when I want clicked the show link the error is
undefined method `post_comments_path' for #<#<Class:0x2aef820>:0x2bd7df8>
Extracted source (around line #25):
<h2>Add a comment:</h2>
<%= form_for([#post, #post.comments.build]) do |f| %>...here it is line number 25
<p>
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
I have two model
post.rb
class Post < ActiveRecord::Base
has_many :comments
validates :title, presence: true,
length: { minimum: 5 }
end
comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
end
I have two controllers
posts_controller.rb
class PostsController < ApplicationController
def new
#post=Post.new
end
def show
#post = Post.find(params[:id])
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update(params[:post].permit(:title, :text))
redirect_to #post
else
render 'edit'
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to posts_path
end
def create
#post = Post.new(post_params)
# it will also works #post=Post.new(params[:post].permit(:title,:text))
if #post.save
redirect_to #post
# or this command also works redirect_to action: :show, id: #post.id
else
render 'new'
end
end
def index
#posts = Post.all
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
comments_controller.rb
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create(params[:comment].permit(:commenter, :body))
redirect_to post_path(#post)
end
end
my routes.rb file is
Blog::Application.routes.draw do
resources :posts do
resources :comments
end
I have two migration files
create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :text
t.timestamps
end
end
end
create_comments.rb
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :post
#above line sets foreign key column for the association between the two models.
t.timestamps
end
#and bellow add_index line sets up an index for this association column.
add_index :comments, :post_id
end
end
my show.html.erb file is
<p>
<strong>Title:</strong>
<%= #post.title %>
</p>
<p>
<strong>Text:</strong>
<%= #post.text %>
</p>
<h2>Comments</h2>
<% #post.comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<% end %>
<h2>Add a comment:</h2>
<%= form_for([#post, #post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Edit Post', edit_post_path(#post) %> |
<%= link_to 'Back to Posts', posts_path %>
I used associations in the models whenever I am applying associations I am getting problem ,I am new to ruby as well as rails.I am using Rails4,Eclipse,Windows Xp(sp3) and mysql5.6 ,I am getting the above error when I want clicked the show link the error is I used associations in the models whenever I am applying associations I am getting problem ,I am new to ruby as well as rails.I am using Rails4,Eclipse,Windows Xp(sp3) and mysql5.6 ,I am getting the above error when I want clicked the show link the error is
I have a feeling you missed the part about nested resources. As in:
resources :posts do
resources :comments
end
This means the routes generated by resources :comments are nested within your posts, which results in URLs like this:
/posts/1/comments
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.