So I have a User model generated with devise, and I am using Wicked gem to give me multiform option on taking more data from the user and storing it in the user model.
Everything is working fine but know I'm trying to add another model where user has many degree. I am using cocoon gem to allow me to add extra degrees. I am able to go to the multiform page and enter degree information and even add many more degrees to the user, but when i submit the form i get an error;
param is missing or the value is empty: user
Everything else actually gets saved am i can view the user and the rest of the fields entered but non of the degrees.
user model:
has_many :degrees
accepts_nested_attributes_for :degrees, reject_if: :all_blank, allow_destroy: true
degree model:
belongs_to :user
user_steps_controller (this is the wicked gem controller):
class UserStepsController < ApplicationController
include Wicked::Wizard
steps :personal, :avatar_and_about_yourself, :social, :education
def show
#user = current_user
render_wizard
end
def update
#user = current_user
#user.update_attributes(user_params)
render_wizard #user
end
private
def user_params
params.require(:user).permit(:name, :middlename, :lastname, :avatar, :aboutMe, :twitterlink, :githublink, :stackoverflowlink, :mediumlink, :dribblerlink, degrees_attributes: [:id, :degreeName, :university, :level, :done, :_destroy])
end
end
Registration controller (for devise):
class Users::RegistrationsController < Devise::RegistrationsController
# before_filter :configure_sign_up_params, only: [:create]
# before_filter :configure_account_update_params, only: [:update]
# GET /resource/sign_up
def new
super
end
# POST /resource
def create
super
end
# PUT /resource
def update
super
end
protected
# The path used after sign up.
def after_sign_up_path_for(resource)
user_steps_path
end
# The path used after sign up for inactive accounts.
def after_inactive_sign_up_path_for(resource)
user_steps_path
end
def sign_up_params
params.require(:user).permit(:email, :password, :password_confirmation, :name, :middlename, :lastname, :avatar, :aboutMe, :twitterlink, :githublink, :stackoverflowlink, :mediumlink, :dribblerlink, degrees_attributes: [:id, :degreeName, :university, :level, :done, :_destroy])
end
end
Im getting an error in the user_steps_controller:
ActionController::ParameterMissing in UserStepsController#update
param is missing or the value is empty: user
and that the error is within this line:
def user_params
params.require(:user).permit(:name, :middlename, :lastname, :avatar, :aboutMe, :twitterlink, :githublink, :stackoverflowlink, :mediumlink, :dribblerlink, degrees_attributes: [:id, :degreeName, :university, :level, :done, :_destroy])
end
Also how would i go and view the entered fields, for example if i wanted to view user name it is:
<%= #user.name %>
but how would i show each degree? is it just a loop?
<% #users.degree.each do |degree| %>
Terminal log:
Started PATCH "/user_steps/education" for ::1 at 2016-02-09 11:23:29 +0000
Processing by UserStepsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"EXN7ts6xPVK8vkC7q6UcNleJJWLUtKmOw41T0qsDqXCrPJ0vIHrB/6xIfpp/o+cXKR47F+6LxUY5LjXlCobKZQ==", "commit"=>"Update User", "id"=>"education"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 16]]
Completed 400 Bad Request in 2ms (ActiveRecord: 0.2ms)
ActionController::ParameterMissing (param is missing or the value is empty: user):
app/controllers/user_steps_controller.rb:20:in `user_params'
app/controllers/user_steps_controller.rb:13:in `update'
This is too long to comment, I fully expect to update it.
The problem you have is that your form submission does not include any user params:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"EXN7ts6xPVK8vkC7q6UcNleJJWLUtKmOw41T0qsDqXCrPJ0vIHrB/6xIfpp/o+cXKR47F+6LxUY5LjXlCobKZQ==", "commit"=>"Update User", "id"=>"education"}
This might be Wicked, but judging form your spurious use of RegistrationsController, I'd imagine it could be to do with formatting etc:
--
If you're updating your current_user, you should not be invoking your registrations controller. That is for registrations -- you should be using your users controller:
#config/routes.rb
resource :user_steps, path: "user", only: [:show, :update] #-> url.com/user (singular resource)
#app/controllers/user_steps_controller.rb
class UserStepsController < ApplicationController
def show
end
def update
#user = current_user.update user_params
render_wizard #user
end
private
def user_params
params.require(:user).permit(:name, :middlename, :lastname, :avatar, :aboutMe, :twitterlink, :githublink, :stackoverflowlink, :mediumlink, :dribblerlink, degrees_attributes: [:id, :degreeName, :university, :level, :done, :_destroy])
end
end
This is just the controller; you need to look at how the form is being rendered & passed.
If you're sending data with the above code, you'll want to pull your form HTML and show how Wicked is working with it.
You need to be looking in app/views/users/show.html.erb for the form to display, not /app/views/registrations
Related
What I want to achieve
I would like to save user information to db using a wizard form(multistep form).
I am currently creating my own app and I created a wizard form(3 pages) to save user information using device gem.
First page: basic info such as a profile picture and name
Second page: address info(using Automatic address input function)
Third page: completed page
It was working fine until I created other models and did association and also installing carrierwave gem. I am not sure what led to this but after doing things above I could not save user info to the db anymore.
Issues that occurs and error messages that I get
Firstly, I did not get any error messages on the screen but data was not saved.
Although there was no error messages on the screen, in the terminal, I got ROLLBACK as below.
(0.2ms) BEGIN
User Exists (0.3ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY 'aa#aa' LIMIT 1
(0.2ms) ROLLBACK
Completed 422 Unprocessable Entity in 117ms (ActiveRecord: 0.7ms)
To check the error, I changed .save to .save! and I got error message below.
ActiveRecord::RecordInvalid in Users::RegistrationsController#create_address
Validation failed: Image can't be blank
my coding
【registrations_Controller.rb】
# frozen_string_literal: true
class Users::RegistrationsController < Devise::RegistrationsController
# before_action :configure_sign_up_params, only: [:create]
# before_action :configure_account_update_params, only: [:update]
def new
#user = User.new
end
def create
#user = User.new(sign_up_params)
unless #user.valid?
flash.now[:alert] = #user.errors.full_messages
render :new and return
end
session["devise.regist_data"] = {user: #user.attributes}
session["devise.regist_data"][:user]["password"] = params[:user][:password]
#address = #user.build_address
render :new_address
end
def create_address
#user = User.new(session["devise.regist_data"]["user"])
#address = Address.new(address_params)
unless #address.valid?
flash.now[:alert] = #address.errors.full_messages
render :new_address and return
end
#user.build_address(#address.attributes)
#user.save!
session["devise.regist_data"]["user"].clear
sign_in(:user, #user)
end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
# def update
# super
# end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_up_params
# devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
# end
# If you have extra params to permit, append them to the sanitizer.
# def configure_account_update_params
# devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
# end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
protected
def address_params
params.require(:address).permit(:zipcode, :prefecture_code, :city,:district, :building, :room)
end
end
【Application_controller.rb】
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
def after_sign_in_path_for(resource)
posts_path
end
def after_sign_out_path_for(resource)
root_path
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname,:first_name,:last_name, :first_name_kana, :last_name_kana,:birthday,:image])
end
end
【user.rb】
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :nickname,:first_name,:last_name, :first_name_kana, :last_name_kana,:birthday,:image ,presence: true
has_one :address
has_many :posts
has_many :messages
has_many :group_users, dependent: :destroy
has_many :groups, through: :group_users, dependent: :destroy
include JpPrefecture
jp_prefecture :prefecture_code
mount_uploader :image, ImageUploader
def prefecture_name
JpPrefecture::Prefecture.find(code: prefecture_code).try(:name)
end
def prefecture_name=(prefecture_name)
self.prefecture_code = JpPrefecture::Prefecture.find(name: prefecture_name).code
end
end
【address.rb】
class Address < ApplicationRecord
belongs_to :user, optional: true
validates :zipcode, :prefecture_code, :city,:district,presence: true
mount_uploader :image, ImageUploader
end
My guess
My guess is that the since the error messages is "image can't be blank", the image that was registered at the first page is not correctly transferred to the second page.
What I've tried
Despite the fact that I suspect that the error is occurred due to the issue related to transferring image among wizard form, I tried several things below...
■model
・association is not done correctly ?
Checked if the association is written correctly.
I check if there are has_many(one)×belong_to relationship written in the model.
・Not allowed nil for external key?
add "optional: true" after belong_to
・image is not transferred to the second page?
add "mount_uploader :image, ImageUploader" in the address.rb as well
■Controller
・Image is not saved?
Checked if there is ":image" written in devise_parameter_sanitizer of application_controller
Although I keep try solving by myself, I look forward to hearing some advice from you.
Thank you in advance!
I am new to rails and finishing up the Michael Hartl tutorial and creating some variations on the basic app from the book. One thing I am trying to do is create a set of model associations that is three deep (user-> colleciotn-> pictures ->). I am also trying to place my pictures form in the view for showing collections. I tried following the pattern used in the book for the User to collection relationship, but have had several issues. First, I could not use the Form_with tag (form_with(model: #picture, local: true)) and ended up writing out the path (form_with(url:"/pictures/create", method: "post")). Also, I used a hidden field tag to pass the collection_id to the "create" method.
My issue now seems to be that it is not saving the #picture data in the Picture Controller. Here is the line I think is suspect:
#picture= #collection.pictures.build
Here is a summary/my understanding of what I am trying to do.
render the Picture form on the Controller show page
Post the form date to the picture model, while also passing the
Controller object ID to the controller so to preserve the picture to controller relationship
Call the Controller object using the controller ID that was sent in
params
Save the Picture params to the Picture model with .build and flash a success message
From the logs, I believe the issue is with my use of the .build (highlighted below in code).
I will provide the code below for all of the elements of the app, as well as the log. I could really use some help figuring out what I am doing wrong. Let me know if there is anything else I should share.
Models
Picture Models
class Picture < ApplicationRecord
belongs_to :collection
validates :collection_id, presence: true
validates :picture_title, presence: true, length: { maximum: 30}
end
Collection Model
class Collection < ApplicationRecord
belongs_to :user
has_many :pictures, dependent: :destroy
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :collection_title, presence: true, length: { maximum: 30 }
end
User Model
class User < ApplicationRecord
has_many :collections, dependent: :destroy
has_many :pictures, through: :collections
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: true
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
def forget
update_attribute(:remember_digest, nil)
end
def feed
Collection.where("user_id = ?", id)
end
end
Routes
Rails.application.routes.draw do
get 'sessions/new'
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
post '/pictures/create', to: 'pictures#create'
resources :users
resources :collections
resources :pictures
resources :users do
resources :collection
end
resources :collections do
resources :pictures
end
end
Picure Controller
def create
#collection = Collection.find(params[:collection_id])
#picture= #collection.pictures.build
if #picture.save!
flash[:notice] = "Picture was successfully added."
redirect_to request.referrer
else
flash[:alert] = "Picture could not be saved."
redirect_to request.referrer
end
end
private
def correct_user
#collection = current_user.collections.find_by(id: params[:id])
redirect_to root_url if #collection.nil?
end
def picture_params
params.require(:picture).permit(:picture_title)
end
end
Collections Controller
class CollectionsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy, :show, :index]
before_action :correct_user, only: [:destroy, :show]
def show
#collection = Collection.find(params[:id])
#picture= Picture.new
end
def create
#collection = current_user.collections.build(collection_params)
if #collection.save
flash[:success] = "Image collection created!"
redirect_to root_url
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'static_pages/home'
end
end
def destroy
#collection.destroy
flash[:success] = "Collection deleted"
redirect_to request.referrer || root_url
end
private
def collection_params
params.require(:collection).permit(:collection_title)
end
def correct_user
#collection = current_user.collections.find_by(id: params[:id])
redirect_to root_url if #collection.nil?
end
end
**Picture Form **
<%= form_with(url:"/pictures/create", method: "post") do |f| %>
<div class="field">
<%= f.text_field :picture_title, placeholder: "Picture Title" %>
</div>
<%= f.submit "Create Collection", class: "btn btn-primary" %>
<%= hidden_field_tag :collection_id, #collection.id %>
<% end %>
Logs
Started POST "/pictures/create" for 99.150.231.55 at 2020-01-04 19:29:08 +0000
Cannot render console from 99.150.231.55! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by PicturesController#create as JS
Parameters: {"authenticity_token"=>"GNDEKiGPVP7EHRtgphGDMIJxbKgnXn2MFSmgTJMIoEo2Owan5THjMIx9N8pKLkS7hmaqJMdwhjqvuOBR/3JaHg==", "picture_title"=>"TEST", "collection_id"=>"10", "commit"=>"Create Collection"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/helpers/sessions_helper.rb:18:in `current_user'
Collection Load (0.1ms) SELECT "collections".* FROM "collections" WHERE "collections"."id" = ? ORDER BY "collections"."created_at" DESC LIMIT ? [["id", 10], ["LIMIT", 1]]
↳ app/controllers/pictures_controller.rb:12:in `create'
Completed 500 Internal Server Error in 6ms (ActiveRecord: 0.2ms | Allocations: 2423)
NoMethodError (undefined method `picture_title=' for nil:NilClass):
app/controllers/pictures_controller.rb:14:in `create'
EDIT
I implemented Max's code corrections, but now getitng the following error:
Started POST "/collections/10/pictures" for 99.150.231.55 at 2020-01-05 17:57:57 +0000
Cannot render console from 99.150.231.55! Allowed networks: 127.0.0.0/127.255.255.255, ::1
(0.1ms) SELECT sqlite_version(*)
NoMethodError (undefined method `make_response!' for PicturesController:Class):
A lot of things are off here. First axe this junk:
post '/pictures/create', to: 'pictures#create' # never do this again please.
The route here to create a picture is going to be POST /collections/:collection_id/pictures. Which RESTfully describes that we are creating a picture that belongs to a collection. You already have that route setup by:
resources :collections do
resources :pictures
end
In rails the action is only ever in the path for /edit and /new. All the other actions are defined by the HTTP verb.
class PicturesController < ApplicationController
before_action :set_collection, only: [:new, :create, :index]
# POST /collections/1/pictures
def create
#picture = #collection.pictures.new(picture_params)
if #picture.save
flash[:notice] = "Picture was successfully added."
redirect_to #collection
else
flash.now[:alert] = "Picture could not be saved."
render 'collections/show'
end
end
# ...
private
def set_collection
#collection = Collection.find(params[:collection_id])
end
def picture_params
params.require(:picture).permit(:picture_title)
end
end
Don't do redirect_to request.referrer when a record is not valid (or really at all). Many clients do not send the HTTP referer header and it will make for a really bad user experience as any user input and the validation messages are lost. Most of the time you actually know where you should send the user like in your Collections#destroy method which should probably redirect to the index or the users feed. If you really want redirect back reliably save the location in the session.
The form should read:
<%= form_with(model: [#collection, #picture]) do |f| %>
<div class="field">
<%= f.text_field :picture_title, placeholder: "Picture Title" %>
</div>
<%= f.submit %>
<% end %>
Since the collection id is in the path we don't need to do that hacky garbage of using a hidden input to pass it. This also binds the form to the model instance so that the user input is not lost if the input is invalid.
I have been stuck up with this exception.I am using rails 4.2.5.1 and ruby 2.3.0. I am creating a model using devise in rails. I have override the devise create method. I am getting error in postgres as PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint.I want the ID to be created with the help of parameters i am passing. ID is not getting created. As am new to rails am getting stuck up for hours now.
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"SAiVJEULEa7RsieW+OTW1a/946f2xVbhA/sZWWn3KdX1Wt0Ozx+tq6eQfhTpaAJ+4Cxu2DMnPfqd0Vcle7ow0w==",
"employee"=>{"email"=>"safi123#gmail.com",
"first_name"=>"sss",
"last_name"=>"dddnjnfj",
"phone_number"=>"9944253677",
"alternative_phone_number"=>"9659392682",
"alternative_email_id"=>"dd#gmail.com",
"date_of_joining"=>"12-02-2015",
"date_of_birth"=>"03-02-1999",
"status"=>"Active",
"gender"=>"M",
"blood_group"=>"A +"},
"commit"=>"Sign up"}
Application Controller:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_employee!
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |employee_params|
employee_params.permit :first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number
end
devise_parameter_sanitizer.for(:account_update) do |employee_params|
employee_params.permit :first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number
end
end
end
Registrations Controller
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def index
#employees = Employee.all
end
def create
#employee = Employee.new(employee_params)
if #employee.save
redirect_to :action => :new
else
render 'new'
end
#employee.save
end
# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
params.require(:employee).permit(:first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number)
end
def update
super
end
end
Database schema :
I can understand the ID is not generated and it is not stored in the database. What is the problem here? Can anyone explain me what is the mistake am making?
You are saving the employee record twice. That may be the problem, please save only once.I have given the action please check.
def create
#employee = Employee.new(employee_params)
if #employee.save
redirect_to :action => :new
else
render 'new'
end
/* Here you had saved again. */
end
Your Employee params,
def employee_params
params.require(:employee).permit(:first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number)
end
Now you will get the id through params and it will be saved.
I have a devise model that has a nested form (supp_form is the nested object) on sign up. When I submit the form I am getting the following error:
WARNING: Can't mass-assign protected attributes for Business: supp_form_attributes, terms_of_service
app/controllers/businesses/registrations_controller.rb:11:in `create'
I am using the nested_form gem and it seems as if my form is passing field data through to the console. My parameters after submit look like the following:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XXX", "business"=>{"type"=>"Business", "supp_form_attributes"=>{"title"=>"mr.", "first_name"=>"jane", "last_name"=>"doe", "mobile_phone_number"=>"94034903", "loan_agreement_authorization"=>"1", "work_phone_number"=>"49034903", "business_industry"=>"Natural Resources and Mining", "legal_structure"=>"Sole Proprietorship", "employee_count"=>"5 to 10", "years_in_business"=>"5+ years", "business_address"=>"72 pentland rd", "business_city"=>"Waterdown", "business_postal_code"=>"l0r2h5", "business_province"=>"ON"}
business.rb
class Business < User
# Associations
has_one :supp_form
has_many :loan_applications
has_many :transactions
# Nested attributes
accepts_nested_attributes_for :supp_form, :loan_applications
# After save action
after_save :create_account
# Validations
validates_acceptance_of :terms_of_service
validate :terms_of_service, presence: true
end
supp_form.rb
class SuppForm < ActiveRecord::Base
# Associations
belongs_to :business
# Validations
validates_acceptance_of :terms
validates :business_id, :first_name, :last_name, :work_phone_number, :business_address, :business_postal_code, :business_city, presence: true
end
registraionts_controller.rb
class Businesses::RegistrationsController < Devise::RegistrationsController
before_filter :update_sanitized_params
def new
build_resource({})
resource.build_supp_form
respond_with self.resource
end
def create
super
resource.update_attribute(:railsid, '%010d' % rand(10 ** 10))
end
private
def update_sanitized_params
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :password_confirmation, :type, :confirmed_at, :business_name, :terms, :railsid, :terms_of_service,
supp_form_attributes: [:business_id, :title, :loan_agreement_authorization, :first_name,
:last_name, :work_phone_number, :business_address, :business_postal_code,
:business_city, :business_name, :years_in_business, :legal_structure,
:business_industry, :employee_count, :mobile_phone_number, :business_province])}
end
def after_sign_up_path_for(resource)
business_root_path
end
end
supp_forms_controller.rb
class SuppFormsController < ApplicationController
before_filter :authenticate_user!
def new
#suppform = SuppForm.new(supp_form_params)
end
def create
#suppform = SuppForm.create(supp_form_params)
end
private
def supp_form_params
params.require(:supp_form).permit(:business_id, :title, :loan_agreement_authorization, :first_name,
:last_name, :work_phone_number, :business_address, :business_postal_code,
:business_city, :business_name, :years_in_business, :legal_structure,
:business_industry, :employee_count, :mobile_phone_number, :business_province)
end
end
You are using Rails 4 with strong parameters. And you get an error triggered by the protected_attributes gem (or default rails 3 app).
With strong_parameters on place you can remove safety the protected_attributes gem. And remove the configuration if you have it (config.active_record.whitelist_attributes).
I'm working on a Ruby on Rails project and I have two models:
1. User
2. Merchant
their relationships are:
User has_one :merchant
Merchant belongs_to :user
then in my user.rb
attr_accessor :merchant_name
after_create :create_merchant
def create_merchant
create_merchant(name: merchant_name)
end
In my user's form:
= form_for #user do |f|
= f.text_field :merchant_name
= f.text_field :email
= f.text_field :password
the problem is the user and a merchant has been created but the merchant's name is nil
In my Account::RegistrationsController
class Account::RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(resource)
account_users_path
end
private
def registration_params
params.require(:user).permit(:merchant_name)
end
end
I'm getting this error:
Processing by Account::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ht8vHG8I4bz2ylt+mtLC7hilQnK3VnYtcHgSNv8nSeg=", "user"=>{"merchant_name"=>"Zara 123", "email"=>"allen.chun#hotmail.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"}
Unpermitted parameters: merchant_name
I wouldn't override the create_merchant method if I were you, try something like this:
after_create -> { create_merchant!(:name => self.merchant_name) }
and make sure your merchant_name is permitted in the users controller, something like this:
def create
#user = User.new(user_params)
if #user.save
redirect_to #user
else
render :new
end
end
private
def user_params
params.require(:user).permit(:merchant_name, :email, :password, :password_confirmation)
end
Perhaps it should be
attr_accessor :merchant_name
after_create :create_merchant
def create_merchant
build_merchant(name: merchant_name)
save
end
create_association hasn't supported in rails 4
Also don't forget to permit merchant_name. According to this info:
class Account::RegistrationsController < Devise::RegistrationsController
before_action :configure_permitted_parameters
protected
def after_sign_up_path_for(resource)
account_users_path
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :merchant_name
end
end