Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data from a database in rails

I have created a rail application i am connecting to mysql database

i already have 2 tables users and history

how can i fetch data from these tables i can save data to database with

def register

        if(params[:register])
            @registermsg=Users.where(:username=>params[:register][:username])
            if  @registermsg.length>0
                flash[:success] = "Username exists:#{params[:username]}:"

            else
                @reg = Users.create(user_params)
                @reg.save
                flash[:success] = "success:#{params[:register][:username]}:"

            end

        end
  end

  def user_params
      params.require(:register).permit(:username, :password, :password2)
    end

but when i am fetching data from users

def login

        if session[:user]

            redirect_to '/dash'
        end 

        if(params[:login])

            @login1=Users.where("username=? AND password=?",params[:login][:username],params[:login][:password])
            if  @login1.length==1
                session[:user] = @login1
                hist = History.create(userid: **@login1.id**, ip: request.remote_ip )
// here @login1.id is giving me error

                redirect_to '/dash'
            else
                flash[:success] = "Wrong"


            end

        end
  end

@login1=Users.where("username=? AND password=?",params[:login][:username],params[:login][:password])

@login1.to_yaml is printing full data how can i get id,username etc from @login1

presently @login1.id is getting error

I researched in many websites including stack overflow till now i didnt got any solution please help

like image 790
user3797053 Avatar asked Aug 06 '26 16:08

user3797053


1 Answers

Here @login1 is an ActiveRelation object. You will have to call first to get the actual user object

  if  @login1.count==1
      session[:user] = @login1.first
      hist = History.create(userid: @login1.first.id, ip: request.remote_ip )
      redirect_to '/dash'
like image 150
usha Avatar answered Aug 08 '26 10:08

usha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!