Novice
Novice

Reputation: 443

rendering the partials in controller after the validation check

I have two partial views for two different sign up forms. On my home page , based on the link one clicks on, I'm rendering respective form.(views/application/index)

= link_to 'Mentor', new_user_path(user_role: true), :class =>'btn'
= link_to 'Mentee', new_user_path, :class =>'btn'

In views/users/new.html.haml , I'm checking the user role and redirecting to the respective form.

- if params[:user_role]
= render 'mentor'
- else
= render 'mentee'

In the user model I've added validation like this.

class User < ActiveRecord::Base
    email_regex = /\A[\w+\-.][email protected]/i

    validates :cisco_email, :presence   => true,
              :format     => { :with => email_regex,}
    validates :work_city, :presence => true

end

So, when there is any invalid field I want to direct to the same form with a flash message. My controller looks like this.

class UsersController < ApplicationController

   def index
   end

    def show
      @user = User.find(params[:id])
    end

   def new
     @user = User.new
    end

    def create
        @user = User.new(params[:user])    # Not the final implementation!
        if @user.save
            flash[:success] = "Welcome to the CSG Mentoring Tool!"
            redirect_to @user
        else 
        flash[:notice] = "Error regsitering."

             if params[:user][:user_role]
                      render :partial => 'users/mentor'
             else
                render :partial => 'users/mentee'
             end
         end
     end    
 end

When an invalid field entry is there, it is redirecting to 'mentee' page no matter on which page the error is made. Also the entire css styling gets changed and flash is also not displayed

Upvotes: 0

Views: 78

Answers (1)

Pardeep Dhingra
Pardeep Dhingra

Reputation: 3946

Why this is not working? if params[:user][:user_role] render :partial => 'users/mentor' else render :partial => 'users/mentee' end

params[:user][:user_role] is nil.

You can check it using lots of way:

Above your if condition raise params[:user].inspect

Why its nil?

Reason of this is You are passing new_user_path(user_role: true) user_role true, but user_role is not true in mentor form.

params[:user_role] will not set user_role = true field in mentor form.

Set user_role

<%=f.hidden_field :user_role, value: params[:user_role] %>

If its supposed to be true for mentor always

<%=f.hidden_field :user_role, value: true %>

By default flash will make them available to the next request, but sometimes you may want to access those values in the same request. Reference

This works with redirection

flash[:success] = "Welcome to the CSG Mentoring Tool!"

This will work with render

flash.now[:success] = "Welcome to the CSG Mentoring Tool!"

Upvotes: 1

Related Questions