I am trying to create a new record for 'campaign' via the 'customer' as follows. The form submits correctly, however no new campaign record is created for the customer. Any advise would be greatly appreciated.
Models
class Customer::Customer < User
has_one :library, dependent: :destroy
has_many :campaigns, dependent: :destroy
accepts_nested_attributes_for :campaigns, :library, allow_destroy: true
end
class Customer::Campaign < ActiveRecord::Base
belongs_to :customer
end
Customer Controller - Update Method only shown
class Customer::CustomersController < ApplicationController
layout "customer_layout"
def update
session[:return_to] ||= request.referer
#customer = User.find(params[:id])
if #customer.update_attributes(customer_params)
flash[:success] = "Profile updated"
redirect_to #customer
else
flash[:notice] = "Invalid"
redirect_to session.delete(:return_to)
end
end
def customer_params
params.require('customer_customer').permit(:name, :email, :password, :password_confirmation, :country_code, :state_code, :postcode, :first_name, :surname, campaigns_attributes:[:name, :description, :start_date, :complete_date ])
end
end
And the form I am using
<%= form_for #customer do |f| %>
<%= render 'shared/customer_error_messages' %>
<%= f.fields_for :campaign do |builder| %>
<%= builder.label :name, "Campaign Name" %></br>
<%= builder.text_field :name %>
<% end %>
<div class="actions">
<%= f.submit class: "btn btn-large btn-primary"%>
</div>
<% end %>
And the console output (with error, is as follows)
Started PATCH "/customer/customers/38" for 127.0.0.1 at 2014-05-26 23:13:10 +1000
Processing by Customer::CustomersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9ChLYna0/VfZSMJOa2yGgvWTT61XkjoYwlVup/Pbbeg=", "customer_customer"=>{"campaign"=>{"name"=>"My new campaign"}}, "commit"=>"Update Customer", "id"=>"38"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = '0e8b4ba6dc957e76948fc22bae57673404deb9fe' LIMIT 1
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "38"]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "38"]]
Unpermitted parameters: campaign
If this form performs adding only one campaign i guess you should handly add this exect campaign to customer. If you update all campaign model in such way, you should have all your campaigns in array. So it implies another controller action for this.
Another way: to check if params contains field campain and then just add it to customer object:
def update
session[:return_to] ||= request.referer
#customer = User.find(params[:id])
if new_campaign_customer_params.has_key? :campaign
#customer.campaigns << Campaign.new(new_campaign_customer_params)
if #customer.save
flash[:success] = "Profile updated"
redirect_to #customer
else
flash[:notice] = "Invalid"
# you should rerender your view here, set it path
render 'your_view'
end
else
if #customer.update_attributes(customer_params)
flash[:success] = "Profile updated"
redirect_to #customer
else
flash[:notice] = "Invalid"
redirect_to session.delete(:return_to)
end
end
end
def new_campaign_customer_params
params.require('customer_customer').permit(campaign_attributes:[:name, :description, :start_date, :complete_date ])
end
Check this out, not sure it works.
Or maybe it would work how to suggests in comment: change campaigns_attributes => campaign_attributes in customer_params method, and f.fields_for :campaigns in form (belongs to #Nikita Chernov)
Related
I'm not sure why but I cannot save my form input to the database, and I couldn't find any answer so far :), but it works for creating the posts using the console.
Started POST "/posts" for 127.0.0.1 at 2018-05-23 14:04:32 +0300
Processing by PostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"B19yVi1jHtg7068SKFbI3tj28THNdfgGYwUSN+e79Vt/o0ivDUl0D4i71PuLKlZf1wxnEJMVnp+GmH/HcxE6cQ==", "post"=>{"category_id"=>"2", "title"=>"asfaf", "content"=>"asfkja", "photo_cache"=>""}, "commit"=>"Create Post"}
Unpermitted parameter: :photo_cache
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.5ms) BEGIN
Category Load (0.5ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
(0.4ms) ROLLBACK
<%= simple_form_for(#post) do |f| %>
<%= f.collection_select(:category_id, Category.all, :id, :name, {prompt: "Choose a category" }) %><br>
<%= f.label :title %><br>
<%= f.text_field :title, placeholder: "Type the post title here" %><br>
<%= f.label :content %><br>
<%= f.text_area :content, placeholder: "Type the post text here" %><br>
<%= f.input :photo %>
<%= f.input :photo_cache, as: :hidden %><br>
<%= f.submit %>
<% end %>
def new
#post = Post.new
authorize #post
end
def create
#post = Post.new(post_params)
authorize #post
if #post.save
redirect_to #post, notice: "The post was created!"
else
render 'new'
end
end
def post_params
params.require(:post).permit(:title, :content, :category_id, :photo, :user_id)
end
class Post < ApplicationRecord
validates :title, :content, :category_id, presence: true
belongs_to :category
belongs_to :user
mount_uploader :photo, PhotoUploader
end
Console output points the reason - you pass photo_cache parameter while have not permitted it:
Unpermitted parameter: :photo_cache
So, just add :photo_cache to permit list:
params.require(:post).permit(..., :photo_cache)
UPDATE: If Post model belongs to User, it should have foreign key constraint and you must pass user_id parameter to Post.create.
In real apps something like Devise is used for authentication and controller looks like:
class PostsController < ApplicationController
before_action :authenticate_user!
def create
post = current_user.posts.create!(create_params)
# post = Post.new(create_params.merge(user: current_user))
# ...
end
end
Basically what helped is changing the create method
def create
#post = current_user.posts.new(post_params)
authorize #post
if #post.save
redirect_to #post, notice: "The post was created!"
else
render 'new'
end
end
I am newbie on RoR. I try to create answer through word controller by using accepts_nested_attributes_for but when I click submit button, I get nothing and button got disable.
Here is my code.
word.rb
class Word < ApplicationRecord
belongs_to :category
belongs_to :exam
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers
has_many :exam_words, dependent: :destroy
scope :alphabet, ->{order :content}
end
answer.rb
class Answer < ApplicationRecord
belongs_to :wordscope :alphabel, ->{order "content"}
validates :content, presence: true
end
new.html.erb
<% provide(:title, "Create word" )%>
<h1></h1>
<%= form_for #word do |f| %>
<%= f.label :word_content %>
<%= f.text_field :content, class: "form-control" %>
<%= f.fields_for :answers do |answer| %>
<%= answer.label :answer_content %>
<%= answer.text_area :content, class: "form-control" %>
<%= answer.label :is_correct %>
<%= answer.check_box :is_correct %>
<%end%>
<%= f.submit "create", class: "btn btn-primary"%>
<%end%>
words_controller.rb
class WordsController < ApplicationController
before_action :load_category, except: [:show, :new]
def index
#words = #category.words.includes(:answers).paginate(page: params[:page])
end
def new
#word = Word.new
#word.answers.new
end
def show
#word = Word.find_by_id(params[:id])
session[:w_id] = #word.id
end
def create
#word = #category.words.new(word_params)
#word.category_id = session[:cat_id]
#word.exam_id = 1
if #word.save
redirect_to category_path(session[:cat_id])
end
end
def destroy
#word = Word.find(params[:id])
if #word.present?
#word.destroy
end
redirect_to :back
end
def edit
#word = Word.find(params[:id])
end
def update
#word = Word.find(params[:id])
if #word.update_attributes(word_params)
flash[:success] = "Updated"
redirect_to category_path(session[:cat_id])
else
render 'edit'
end
end
private
def word_params
params.require(:word).permit :content,
answers_attributes: [:id, :content, :is_correct]
end
def load_category
#category = Category.find_by id: session[:cat_id]
unless #category
flash[:danger] = t "category_not_found"
redirect_to categories_path
end
end
end
This is what i get in server in terminal
Started POST "/words" for 127.0.0.1 at 2016-11-29 14:52:26 +0000
Processing by WordsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"qr4qCFAh6omymmgJK7aOjZO0HFtkyT3uwB0KGl6EL60MOipdCFgS0l+XwEi7adhPt1uF1TL2RdRGwsK79FX3iw==", "word"=>{"content"=>"new", "answers_attributes"=>{"0"=>{"content"=>"moi", "is_correct"=>"1"}}}, "commit"=>"create"}
Category Load (0.9ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.2ms) begin transaction
Exam Load (0.3ms) SELECT "exams".* FROM "exams" WHERE "exams"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.4ms) rollback transaction
No template found for WordsController#create, rendering head :no_content
Completed 204 No Content in 48ms (ActiveRecord: 2.7ms)
This is what show in my local web
==============SOLVED========================
I just find out how to solve, I forgot optional: true in answer.rd.
class Answer < ApplicationRecord
belongs_to :word, optional: true
scope :alphabel, ->{order "content"}
validates :content, presence: true
end
Trying to learn RoR. Currently adding comments to posts by user. So far I have a posts model, comments model and post_comments model (to associate the two). So for in 'rails console' I can run: (say I set p = Post.first and c = Comment.first)
p.comments << c
This forms an association so it works in the console. I just can't seem to get the comments to form this association from the UI. So far I am creating the comments at "comments/new" (not sure if this is the issue. Do they need to be created on the "show view" for "post").
Here are some code snippets
Controllers
comments_controller.rb
class CommentsController < ApplicationController
def index
#comment = Comment.all
end
def new
#comment = Comment.new
end
def create
#comment = Comment.new(commentParams)
if #comment.save
flash[:success] = "Comment successfully added"
redirect_to comments_path(#comment)
else
render 'new'
end
end
def show
#comment = Comment.find(params[:id])
end
private
def commentParams
params.require(:comment).permit(:comment)
end
end
posts_controller
class PostsController < ApplicationController
before_action :setPost, only: [:edit, :update, :show, :destroy, :sold]
before_action :requireUser, except: [:index, :show]
before_action :requireSameUser, only: [:edit, :update, :destroy, :sold]
def index
#posts = Post.paginate(page: params[:page], per_page: 20)
end
def new
#post = Post.new
end
def create
#post = Post.new(postParams)
#post.user = currentUser
if #post.save
flash[:success] = "Post successfully added."
redirect_to post_path(#post)
else
render 'new'
end
end
def update
if #post.update(postParams)
flash[:success] = "Post successfully updated."
redirect_to post_path(#post)
else
render 'edit'
end
end
def show
end
def edit
end
def sold
#post.toggle(:sold)
#post.save
redirect_to post_path(#post)
end
def destroy
#post.destroy
flash[:danger] = "Item successfully deleted."
redirect_to posts_path
end
private
def postParams
params.require(:post).permit(:title, :price, :description, category_ids:[])
end
def setPost
#post = Post.find(params[:id])
end
def requireSameUser
if currentUser != #post.user and !currentUser.admin
flash[:danger] = "You can only edit or delete your own items"
redirect_to root_path
end
end
end
Models
comment.rb
class Comment < ActiveRecord::Base
belongs_to :post_comments
belongs_to :user
belongs_to :post
end
post_comment.rb
class PostComment < ActiveRecord::Base
belongs_to :post
belongs_to :comment
end
post.rb
class Post < ActiveRecord::Base
belongs_to :user
has_many :post_categories
has_many :categories, through: :post_categories
has_many :post_comments
has_many :comments, through: :post_comments
validates :title, presence: true,
length: { minimum: 4, maximum: 20 }
validates :description, presence: true,
length: { maximum: 1000 }
validates :user_id, presence: true
end
Views
posts/show.html.erb
<p>Comments: <%= render #post.comments %></p>
This renders the partial below
comments/_comment.html.erb
<%= link_to comment.name, comment_path(comment) %>
Finally is the new comment page as it is.
comments/new.html.erb
<h1>New Comment</h1>
<%= render 'shared/errors', obj: #comment %>
<div class="row">
<div class="col-xs-12">
<%= form_for(#comment, :html => {class: "form-horizontal", role: "form"}) do |f| %>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :comment %>
</div>
<div class="col-sm-8">
<%= f.text_area :comment, rows: 3, class: "form-control", placeholder: "Please enter a comment", autofocus: true %>
</div>
</div>
<div class="form-group">
<div class="center col-sm-offset-1 col-sm-10">
<%= f.submit class: "btn btn-primary btn-lg" %>
</div>
</div>
<% end %>
Any help would be greatly received.
Update
Log
Started GET "/posts/2" for ::1 at 2016-01-15 12:39:55 +0000
Processing by PostsController#show as HTML
Parameters: {"id"=>"2"}
[1m[36mPost Load (0.1ms)[0m [1mSELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1[0m [["id", 2]]
[1m[35mUser Load (0.1ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
[1m[36m (0.1ms)[0m [1mSELECT COUNT(*) FROM "posts" WHERE "posts"."user_id" = ?[0m [["user_id", 1]]
[1m[35mCategory Exists (0.1ms)[0m SELECT 1 AS one FROM "categories" INNER JOIN "post_categories" ON "categories"."id" = "post_categories"."category_id" WHERE "post_categories"."post_id" = ? LIMIT 1 [["post_id", 2]]
[1m[36mCategory Load (0.0ms)[0m [1mSELECT "categories".* FROM "categories" INNER JOIN "post_categories" ON "categories"."id" = "post_categories"."category_id" WHERE "post_categories"."post_id" = ?[0m [["post_id", 2]]
Rendered categories/_category.html.erb (0.2ms)
[1m[35mComment Load (0.1ms)[0m SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ? [["post_id", 2]]
Rendered comments/_comment.html.erb (0.1ms)
Rendered posts/show.html.erb within layouts/application (6.5ms)
[1m[36mCategory Load (0.1ms)[0m [1mSELECT "categories".* FROM "categories"[0m
Rendered layouts/_navigation.html.erb (0.9ms)
Rendered layouts/_messages.html.erb (0.1ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 52ms (Views: 50.3ms | ActiveRecord: 0.5ms)
As a comment can belong to a single post only, you do not need an association table (post_comments). You just need a simple one-to-many relationship.
Your post comment would be:
class Post < ActiveRecord::Base
has_many :comments
...
end
And comment would be like this:
class Comment < ActiveRecord::Base
belongs_to :post
...
end
Just make sure that you have the necessary post_id column in the comments table (you can check the db/schema.rb file). If that is missing, you can use the following migration to add it:
class AddPostIdToComments < ActiveRecord::Migration
def change
add_column :comments, :post_id, :integer
add_index :comments, :post_id
end
end
You also need to make sure you keep somewhere the reference to the post, whenever a user tries to create a comment to a post. You can add this in a hidden field to your comments/new.html.erb template. You could set the hidden field in the new action, in PostsController, after passing it through the URL.
So, in your posts/show.html.erb template you would have:
<%= link_to "Add Comment", new_comment_path(post_id: #post.id) %>
In your new action, in PostsController:
def new
#comment = Comment.new(post_id: params[:post_id])
end
And finally the hidden field in your form would be:
<%= f.hidden_field :post_id %>
Finally, add the post_id parameter to the list of permitted parameters in CommentsController.
instead of
In your new action, in PostsController:
def new
#comment = Comment.new(post_id: params[:post_id])
end
you can use this in the form views
<%= form.hidden_field :post_id, value: "#{params[:post_id]}" %>
I have a form that includes two models, one of which is nested in another. When on the development server I submit the form, the submission generates the flash error message:
The form contains 1 error:
* Members organization can't be blank
Each Member belongs to 1 Organization. Might the error have to do with that the organization isn't saved yet when it's trying to save the Member (for a new organization, it's supposed to simulateneously save the organization and member)? Should I add code that sets organization_id for the member (but I would expect #organization.members.build to take care of that)? What am I doing wrong here?
The server log:
Processing by OrganizationsController#create as HTML
Parameters: {"utf8"=>"✓", "organization"=>{"org_name"=>"sadfsdaf", "phone"=>"sdfds", "members_attributes"=>{"0"=>{"username"=>"fsfdsfsad", "email"=>"sfdsdf#sfsdf.com", "fullname"=>"sdfds", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}, "admin"=>"true", "commit"=>"Sign up"}
(0.5ms) begin transaction
Member Exists (0.4ms) SELECT 1 AS one FROM "members" WHERE LOWER("members"."email") = LOWER('sfdsdf#sfsdf.com') LIMIT 1
Member Exists (0.2ms) SELECT 1 AS one FROM "members" WHERE LOWER("members"."username") = LOWER('fsfdsfsad') LIMIT 1
Organization Exists (0.3ms) SELECT 1 AS one FROM "organizations" WHERE LOWER("organizations"."org_name") = LOWER('sadfsdaf') LIMIT 1
Organization Exists (0.2ms) SELECT 1 AS one FROM "organizations" WHERE LOWER("organizations"."phone") = LOWER('sdfds') LIMIT 1
(0.2ms) rollback transaction
Rendered shared/_error_messages.html.erb (1.9ms)
Organization model:
has_many :members, dependent: :destroy
accepts_nested_attributes_for :members, :reject_if => :all_blank, :allow_destroy => true
Member model:
belongs_to :organization
validates :organization_id, presence: true # There are other validations as well, but I don't think they matter for this question.
def send_activation_email
MemberMailer.account_activation(self).deliver_now
end
Organization controller:
def new
#organization = Organization.new
#member = #organization.members.build
end
def create
#organization = Organization.new(organizationnew_params)
if #organization.save
#member.send_activation_email # Method in Member model file.
flash[:success] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
private
def organizationnew_params
params.require(:organization).permit(:org_name,
:phone,
member_attributes: [:email,
:username,
:admin,
:password,
:password_confirmation
])
end
New view:
<%= form_for(#organization) do |f| %>
<%= f.text_field :org_name, %>
<%= f.text_field :phone %>
<%= f.fields_for :members do |p| %>
<%= p.text_field :username %>
<%= p.email_field :email %>
<%= p.password_field :password %>
<%= p.password_field :password_confirmation %>
<%= hidden_field_tag :admin, true %>
<% end %>
<%= f.submit "Sign up", class: "formbutton btn btn-default" %>
<% end %>
On the permitted params, try changing member_attributes to members_attributes. Also on the create action You are referring to #member but its not defined yet.
To debug further more replace your create action with:
def create
return render text: organizationnew_params
end
This way, when you send the form you will get all the permitted params and check if it's what you expected.
To Send the emails replace
#member.send_activation_email
With
#organization.members.each do |single_member|
single_member.send_activation_email
end
3rd Edit
Just use this
def create
#organization = Organization.new(organizationnew_params)
if #organization.save
#organization.members.each do |single_member|
single_member.send_activation_email
end
flash[:success] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
private
def organizationnew_params
params.require(:organization).permit(:org_name,
:phone,
members_attributes: [:id,:email,
:username,
:admin,
:password,
:password_confirmation
])
end
4th Edit
The validation:
When creating members with oraganization ( in the OraganizationsController ), you do not need to validate organization_id because it will be created at the same time of the organization. Unfortunately you will need the validation of the organization_id when adding a new member to the organization. So what we can do is add a condition to the validation:
#member.rb
attr_accessor :require_organization_id
belongs_to :organization
validates :organization_id, presence: true, if: :require_organization_id
How to use it:
member = Member.new(name: "Some Name")
member.valid? #true
member.require_organization_id = true
member.valid? #false
member.organization = Organization.first
member.valid? #true
If you set validation in member model i.e.
validates :organization_id, presence: true
then it looks in member params for organization_id which doesn't present in params of memeber
"members_attributes"=>{"0"=>{"email"=>"sfsa#sfsd.com", "username"=>"fsfdsfsad", "fullname"=>"sdfds", "password"=>"foobar", "password_confirmation"=>"foobar"}}
thats why its showing validation error so remove this line
validates :organization_id, presence: true
from your member model
Also for #member issue you need to do like this
#organization.memebers.each do |member|
member.send_activation_email
end
I have implemented an oath object oriented approach to my rails application using this tutorial. I've also split my User Form into an Edit & Account Form.
User Edit Form
-Name
-Username
-AboutMe
User Account Form
-Email
-Password
-Password Confirmation
Everything seems to be working okay, until I try to Edit a Regular User's Account or Profile. For some reason I keep getting this error.
undefined method `regular_user_path' for #<#<Class:0x007fc1952f6da0>:0x007fc18bf350a8>
I am not sure why this may be happening. Here is my code below.
Models
class User < ActiveRecord::Base
attr_accessible :name, :bio, :avatar, :username
end
class RegularUser < User
has_secure_password
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
VALID_UNAME_REGEX = /^[a-z](\w*[a-z0-9])*$/i
validates :name, length: { maximum: 50 }
validates :username, :presence => true,
:length => { :maximum => 15 },
:format => { :with => VALID_UNAME_REGEX },
:uniqueness => { :case_sensitive => false }
validates :bio, length: { maximum: 50 }
end
Controller
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :profile, :update, :destroy, :following, :followers, :account]
before_filter :correct_user, only: [:edit, :update, :account]
before_filter :admin_user, only: [:destroy]
def edit
#user = User.find_by_username(params[:id])
end
def account
#title = "Account"
#user = User.find_by_username(params[:id])
end
def update
#user = RegularUser.find(current_user.id) ###I think this is causing it
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in #user
redirect_to root_url
else
if URI(request.referer).path == edit_user_path ###redirects to appropriate page
render 'edit'
else
render 'account'
end
end
end
def destroy
User.find_by_username(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
private
def signed_in_user
unless signed_in?
store_location
redirect_to (root_path), notice: "Please sign in."
end
end
def correct_user
#user = User.find_by_username(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
Views
Edit View
<%= form_for #user, :html => { :multipart => true } do |f| %> ###error comes from this line
<%= render 'shared/error_messages', object: f.object %>
<div class="statictitle">Your Profile</div>
<%= f.text_field :username, placeholder: "Username..", :class => "form-control" %>
<%= f.text_field :name, placeholder: "Name", :class => "form-control" %>
<%= f.text_area :bio, placeholder: "About yourself in 160 characters or less...", class: "textinput" %>
<%= f.submit "Update Profile", class: "btn btn-primary" %><br>
<% end %>
Shared Errors
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Routes
resources :users do
member do
get :account
end
end
LOGS
Started PUT "/users/ClickOnComics" for 127.0.0.1 at 2014-02-20 17:17:50 -0800
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"1CUMHhkE10ubS6uuc26fu1yTGn1bABKNqRIJ67EhEO4=",
"user"=>{"email"=>"clickoncomics#gmail.com", "password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"}, "commit"=>"Update Account", "id"=>"ClickOnComics"}
User Load (0.9ms) SELECT "users".* FROM "users"
WHERE "users"."remember_token" = 'Wqodv-nd6EhKseqQf9FhqA' LIMIT 1
User Load (1.1ms) SELECT "users".* FROM "users"
WHERE "users"."username" = 'ClickOnComics' LIMIT 1
RegularUser Load (0.5ms) SELECT "users".* FROM "users"
WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
(0.2ms) BEGIN
RegularUser Exists (2.7ms) SELECT 1 AS one FROM "users" WHERE
(LOWER("users"."username") = LOWER('ClickOnComics') AND "users"."id" != 1)
LIMIT 1
RegularUser Exists (2.7ms) SELECT 1 AS one FROM "users"
WHERE (LOWER("users"."email") = LOWER('clickoncomics#gmail.com') AND "users"."id" != 1) LIMIT 1
(0.2ms) ROLLBACK
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."username" = 'ClickOnComics' LIMIT 1
Completed 500 Internal Server Error in 237ms
NoMethodError (undefined method `errors=' for #<User:0x007fb6fadf87d0>):
app/controllers/users_controller.rb:40:in `update'
In your update action do as suggested below :
def update
#user = RegularUser.find(current_user.id)
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in #user
redirect_to root_url
else
error_messages = #user.errors.messages ### Capture the error messages
#user = User.find_by_username(params[:id]) ### Add this line
#user.errors.messages.merge!(error_messages) ### Set the error messages hash
if URI(request.referer).path == edit_user_path
render 'edit'
else
render 'account'
end
end
end
When your update fails, you need to reset #user to User instance otherwise when you render edit view it will receive RegularUser instance rather than User instance whereas your form is expecting User instance.
Try adding resources :regular_users to your routes.rb file