简体   繁体   中英

How do i get values from a post form and use them in the rails controller

My controller needs to use the values from the form to get user and start a session.

the values do not seem to be posted, the session is never started, the else statement always seems to be executed rather than the if which needs to be executed.

controller

def new
    end

def create
    uid = params[:uid]
    role = params[:role]

    user=User.find_by(userid:uid,role:role)
    if user 

        session[ :user_id]=user.id
        redirect_to controller: 'stuff', action: 'index'
    else
        render 'new', alert:
          "err"
        end
end 

new.html.erb VIEW

<h1 class ="card-header"> Log IN </h1>

            <%= form_for :session, url: sessions_path do |f| %>
            <div class="form-group">
                <%= f.label :uid %>
                <%= f.text_field :uid %>
            </div>

            <div class="form-group">
                <%= f.label :role %>
                <%= f.text_field :password %>
            </div>



            <div class="form-group">
                <%= submit_tag 'Log In' %>                
            </div>
            <% end %>
        </div>

routes

resources :sessions

your uid and role parameter will be available inside a symbol called session

so the params will look like this


params: {
# other  symbols
  session: {
     uid: // your uid,
     role: // your role
  }
}

so when you access the uid and role like this

uid = params[:uid]
role = params[:role]

it will be nil since they are stored inside the session s symbol.

so the correct way to access them is like this

def create
    uid = params[:session][:uid]
    role = params[:session][:role]

    user=User.find_by(userid:uid,role:role)
    if user 

        session[ :user_id]=user.id
        redirect_to controller: 'stuff', action: 'index'
    else
        render 'new', alert:
          "err"
        end
end 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM