One Model and two controller validation Ruby on Rails? - ruby-on-rails

One thing that confuses me the most is when doing validation in one model with two controllers. I have a login system which register and logs users in. There both use the same model but both does not use the same amount of HTML widgets. One controller contains password, retype password, user name, first & second name and so on. The second controller uses only the user name and password fields. How would you do validation in the same model for this situation?
Thank you
here is the controller that register new users:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
redirect_to '/cool'
else
#user = Newuser.new
#user.valid?
#user.errors.messages
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :salt, :firstname, :secondname, :address, :postcode)
end
end
second controller:
class LoginsController < ApplicationController
before_filter :authorize
def index
#rentals = Rental.where(user_id: current_user.id).limit(5)
#buys = Buy.where(user_id: current_user.id).limit(5)
#users = User.where(id: current_user.id)
#buyGames = BuyGame.where(user_id: current_user.id).limit(5)
end
def destroy
#user = User.find(params[:id])
#user.destroy
redirect_to '/logout'
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update(account_params)
redirect_to '/cool'
else
render 'edit'
end
end
private
def account_params
params.require(:user).permit(:name, :email, :password, :salt, :firstname, :secondname, :address, :postcode)
end
end
Here is my model:
class User < ApplicationRecord
has_secure_password
end

One way to go is to remove validations from the model and put them in form objects. For this case, you'll have two form objects, each with its own set of validations. And you use the appropriate one in respective controllers. Something along these lines:
# logins_controller
def update
login_form = FormObjects::LoginForm.new(login_params)
if login_form.valid?
redirect_to '/cool'
else
render 'edit'
end
end
# users controller
def create
signup_form = FormObjects::SignupForm.new(user_params)
if signup_form.save
redirect_to '/cool'
else
render 'new'
end
end
# signup_form
module FormObjects
class SignupForm
include ::ActiveMode::Model
validate_presense_of :email, :password, :password_confirmation, :address, :whatever_else
def save
# create user here
end
end
end
# login_form
module FormObjects
class LoginForm
include ::ActiveMode::Model
validate_presense_of :email, :password
end
end

You can simply specify validations on actions, that is:
validates :first_name, presence: true, on: :create # which won't validate presence of first name on update or any other action

I believe the trick you are looking for is to define validation actions on create/update of the model. Something roughly along these lines:
class User < ActiveRecord::Base
# These are example validations only; replace with your actual rules.
validates :password, confirmation: true
validates_presence_of :username
validates :first_name, presence: true, format: {with: /.../}, on: create
validates :last_name, presence: true, format: {with: /.../}, on: create
end
...However, I am unclear why you would want to do this in your specific example. It would be advisable to always run all validation checks on fields like first_name, to help maintain data integrity.

Related

Partial validations in multistep forms (Wizard)

I have a multistep form, which I created with wizard. Basically the first tep of the form is user/sign_up - which in my understanding not a step yet. After hitting the sign-up button, user moves to the "real" first step, which is :address.
class UserStepsController < ApplicationController
include Wicked::Wizard
steps :address
def show
#user = current_user || User.from_omniauth(request.env["omniauth.auth"])
render_wizard
end
def update
#user = current_user || User.from_omniauth(request.env["omniauth.auth"])
#user.update!(user_params)
render_wizard #user
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :street, :house_number, :city, :zip_code)
end
def redirect_to_finish_wizard(options = nil, params = nil)
redirect_to new_user_profile_path(current_user)
end
end
This is basically the end of the form already. All gets saved to the user. Now I am stuck with validations.
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:omniauthable, omniauth_providers: %i[facebook]
has_one :profile, dependent: :destroy
after_create :create_profile
accepts_nested_attributes_for :profile
validates :first_name, presence: true
validates :last_name, presence: true
validates :street, presence: true
validates :house_number, presence: true
validates :city, presence: true
validates :zip_code, presence: true
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0, 20]
name = auth.info.name
user.first_name = name.split(" ")[0]
user.last_name = name.split(" ")[1]
end
end
end
I would love to work with the the conditional validations in my model and only validate presence if on a certain step. This should be easy, as I theoretically only have one step, which is address. All I find on the internet, is way too complicated. Question is, do I have to somehow change user/sign_up to a first step in the form and address would be the second step? Or is it fine like this? And if so, can I just add the "if" statements to the address attributes in my validations, somehow defining what is the address step? Would it work like this?
def on_address_step?
wizard.steps = wizard.steps.first
end
Or how do I define it? The validations would look like this then:
validates :first_name, presence: true
validates :last_name, presence: true
validates :street, presence: true, if: :on_address_step?
validates :house_number, presence: true, if: :on_address_step?
validates :city, presence: true, if: :on_address_step?
validates :zip_code, presence: true, if: :on_address_step?
This is surely not that easy. For now this also doesn't work. How do I need to change it? Thanks.
P.S: here is also my Users Controller:
class UsersController < ApplicationController
def index
#users = User.all
end
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
session[:user_id] = #user.id
redirect_to user_steps_path
else
render :new
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :street, :house_number, :city, :zip_code)
end
end
If filling in the address is a completely separate process I would just branch the address out into its own model and controller.
class User < ApplicationRecord
# ...
has_one :address
end
class Address < ApplicationRecord
# ...
belongs_to :user
validates :first_name, :last_name, :street,
:house_number, :city, :zip_code, presence: true
end
This avoids turning your user model into even more of a god object and removes the need for the conditional validation that makes your model much more aware of the UX steps than it should be.
# routes.rb
resources :addresses, only: [:new, :create]
class UsersController < ApplicationController
# ...
def create
#user = User.new(params[:user])
if #user.save
session[:user_id] = #user.id
redirect_to new_address_path
else
render :new
end
end
end
class AddressesController < ApplicationController
# You should have some sort of method that checks if the user
# is signed in and redirect otherwise
before_action :authenticate_user!
# GET /addresses/new
def new
# I'm assuming you have some sort of method to fetch the signed in user
#address = current_user.build_address
end
# POST /addresses
def create
#address = current_user.build_address(address_params)
if #address.save
redirect_to '/somepath'
else
render :new
end
end
def address_params
params.require(:address).permit(
:first_name, :last_name, :street,
:house_number, :city, :zip_code
)
end
end
<%= form_with(model: #address) %>
# ... inputs
<% end %>
I doubt you really want the complexity involved with using Wicked which is ok if you really need a long multiple step form but in this case there is a far simpler and better design choice.

Can Access data of associated model in console but not in app

In my app i have two types of users: students and companies.
During the registration process, i manage with the wicked gem, the user is asked to fill in data depending on the accounttype (student or company) he chose.
For example, a student have to fill in his university, a company have to fill in the amount of employers.
When the registration process is finished, everything is fine, but somehow i cant access the data of the user which chose accounttype 2 - company.
The data is stored in two seperated associated models:
For students: accountinfo (ye i know its against convention and should have the name account_info)
For companies: accountinfos_company (ye i know, weird pluralization .. but it does the trick and i am not confused by it)
Everything works fine for the students. I am able to fill in data and the data is properly saved within a nested form. Same goes for the companies but unfortunately i am not able to output the data of accountinfos_company in my app. What i can do is for example:
#user.accountinfo.description
For student-accounts. But if I try:
#user.accountinfos_company.description
The output fails with an error
undefined method `accountinfos_company' for #<User::ActiveRecord_Relation:0x007fc1851e6e20>
SOMEHOW I am able to output the data of the particular user via console like: User.last.accountinfos_company.description. I copied every step I made for the first associated model, the data gets properly saved but I am not able to access it inside the app.
I thought it might be something missing, some definition or sth like this but as far as i can see, everything is fine.
users_controller.rb (User association stuff gets created in another controller)
class UsersController < ApplicationController
before_action :authenticate_user!
def index
redirect_to root_path
end
def create
#user = User.create( user_params )
end
def show
#user = User.find(params[:id])
if #user.not_complete?
redirect_to user_steps_path
else
render 'show'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
# might be the right way?
#user.update(user_params)
if #user.update(user_params)
redirect_to User.find(params[:id]), notice: 'Profil bearbeitet.'
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :accounttype,
:accountinfo, :accountinfos_company, :profile_image, :active, accountinfo_attributes:[:id], accountinfos_company_attributes:[:id])
end
end
user_steps_controller.rb
class UserStepsController < ApplicationController
include Wicked::Wizard
steps :welcome, :info
before_action :authenticate_user!
def show
#user = current_user
render_wizard
end
def create
#user = current_user
if #user.accounttype == 1
#accountinfo = #user.accountinfo.create(user_params)
elsif #user.accounttype == 2
#accountinfos_company = #user.accountinfos_company.create(user_params)
end
end
def update
#user = current_user
#user.update(user_params)
render_wizard #user
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :accountinfo, :accountinfos_company,:profile_image, :active, accountinfo_attributes:[:id, :city, :competence, :description, :university], accountinfos_company_attributes:[:id, :city, :company_type, :description, :company_name, :employer_amount])
end
private
def redirect_to_finish_wizard_path
redirect_to root_path, notice: "Danke für deine Zeit!"
end
end
user.rb
class User < ApplicationRecord
has_one :accountinfo
has_one :accountinfos_company
has_many :offer_posts
has_many :search_posts
accepts_nested_attributes_for :accountinfo, update_only: true
accepts_nested_attributes_for :accountinfos_company, update_only: true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_presence_of :first_name, :last_name, :email, :accounttype
end
accountinfo.rb and accountinfos_company.rb
belongs_to :user
I dont know if i have something missed but yeah.
If you could help me i would be really glad.

how validation is done using wicked?

I have a users_controller and a user_steps_controller which has three steps :business, :payment and :login
In the user.rb model
class User < ActiveRecord::Base
validates_presence_of :fname, :lname, :email, :mob, :country, :state, :suburb, :postal ,:add
end
while checking validation if i put some random values then also it is giving errors
Fname can't be blank
Lname can't be blank
Email can't be blank
Mob can't be blank
Country can't be blank
State can't be blank
Suburb can't be blank
Postal can't be blank
Add can't be blank
Please help me out
This is my users_controller
def new
#user = User.new
end
def create
#user = User.new(params[:id])
if #user.save
session[:user_id]= #user.id
#user.update_attributes(user_params )
redirect_to user_steps_path
else
render :new
end
end
private
def user_params
params.require(:user).permit( :fname, :lname, :email, :mob, :gender_male, :gender_female, :country, :state, :suburb, :postal ,:add, :cmpyname, :abnacn, :cmpyadd, :cmpydet,:cash, :paypal,:bsb,:usrname,:password_hash, :password_salt, :selcat, :protit, :prodes)
end
user.rb
class User < ActiveRecord::Base
validates :fname, :lname, :email, :mob, :country, :state, :suburb, :postal ,:add, :presence => true
attr_accessor :current_step
validates_presence_of :cmpyname, :abnacn, :cmpyadd, :cmpydet, if: -> { current_step?(:business) }
validates_presence_of :usrname,:password_hash, :password_salt, :selcat, :protit, :prodes, if: -> { current_step?(:login) }
def current_step?(step_key)
current_step == step_key
end
end
user_steps_controller
class UserStepsController < ApplicationController
include Wicked::Wizard
steps :business, :login, :payment
def show
#user = current_user
render_wizard
end
def update
#user = current_user
params[:user][:current_step] = step
#user.update_attributes(user_params )
render_wizard #user
end
private
def user_params
params.require(:user).permit( :cmpyname, :abnacn, :cmpyadd, :cmpydet,:cash, :paypal,:bsb,:usrname,:password_hash, :password_salt, :selcat, :protit, :prodes)
end
end
user.rb
def current_step?(step_key)
current_step == step_key
end
user_steps_controller.rb
class UserStepsController < ApplicationController
include Wicked::Wizard
steps :personal, :social
def show
#user = current_user
render_wizard
end
def update
#user = current_user
params[:user][:current_step] = step
#user.attributes = user_params
render_wizard #user
end
private
def redirect_to_finish_wizard(options = nil)
redirect_to root_url, notice: "Thank you for signing up."
end
def user_params
params.require(:user).permit(:name, :current_step, :date_of_birth, :bio, :twitter_username, :github_username, :website)
end
end
This method will work for you.
Your real problem is here:
#user = User.new(params[:id])
I'm assuming params[:id] is nil, because otherwise that would fail. Basically, your instantiating a User with no data supplied and trying to save it. So clearly those validations you have supplied will fail. If you're actually submitting a form with user data you need to pass user_params you've already defined as follows:
#user = User.new(user_params)
If you need to have validations occur on your User model in different steps, you'll need to have the validations run conditionally dependent on the state of the form:
class User
attr_accessor :current_step
validates_presence_of :business_related_attr, if: -> { current_step?(:business) }
def current_step?(step_key)
current_step.blank? || current_step == step_key
end
end

Rails password can't be blank error

I am trying to create a user signup form in Rails 4.1.6. I keep getting a 'password can't be blank' error. I can see that both the password and password_confirmation are in the params hash but not in the params[:user] sub-hash. I cannot figure out why for the life of me. Any help will be greatly appreciated.
User Model:
class User < ActiveRecord::Base
belongs_to :company
has_secure_password
end
Users Controller:
class UsersController < ApplicationController
respond_to :json
def index
#users = User.all
respond_with(#users)
end
def create
#user = User.new(user_params)
#user.save
respond_with(#user)
end
private
def user_params
params.require(:user).permit(:given_name, :family_name, :email, :password, :password_confirmation)
end
end
It sounds like your parameters are not being sent to the server correctly.
password should be sent as user[password] and password_confirmation should be sent as user[password_confirmation].
See documentation for hash and array parameters.
Alternatively, adding wrap_parameters to the controller will wrap parameters into a nested hash.
wrap_parameters :user, include: [:given_name, :family_name, :email, :password, :password_confirmation]
See documentation for ActionController::ParamsWrapper.

Unknown attribute rails 4

im new into Rails 4 development and rails in general. I red official "getting started with rails" guide where it is shown how to create blog. So I want to do my own from 0 registration, auth system.
While creating new user I get this error. I do not understand what I am doing wrong. Any advice?
Git repo:
https://github.com/pumpurs/auth
ActiveRecord::UnknownAttributeError in UsersController#create
unknown attribute: password
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user].permit(:password, :email, :password_confirmation))
end
private
def user_params
params.require(:user).permit(:password, :email, :password_confirmation)
end
end
Model file:
class User < ActiveRecord::Base
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def enrypt_password
if password.present?
self.password_salt = BCript::Engine.generate_salt
self.password_hash = BCript::Engine.generate.hash_seret(password, password_salt)
end
end
end
You need to add attr_accessor :password to your User model, to provide a non-db-backed attribute to use to base your db-backed password_hash attribute off of.

Resources