Get any id of any user in the database

I am new to rails and have a task that asks me to send an invitation to any user to be an administrator on my log, here is my code snippet

def invite
    inviteUser = { 'user_id' => current_user.id, 'Magazine_id' => params[:id] }
    CollaborationInvitation.create(inviteUser)
    @magazine = Magazine.find(params[:id])
    redirect_to :back
    rescue ActionController::RedirectBackError
    redirect_to root_path
end

      

I need to replace current_user.id

with one that refers to whatever user id that exists in my database in order to send him an invitation to be an administrator with me. I tried to add @User=Users.All

and then pass it as a variable, but it got me wrong, I tried a lot of things, but every time I get an error other than addingcurrent_user.id

ps: I am using for authentication

+3


source to share


3 answers


You've asked a couple of things, and it confuses a little what you want to do.

This is how you get all the record IDs in the model.

Rails4: User.ids

Rails3: User.all.map(&:id)

Or (not sure what #pluck

is in Rails 3 or not)

User.pluck(:id) 

      



If you want to get a random user (you mentioned "any user") you could do.

User.find(User.pluck(:id).sample)

      

Although I think what you really want to do is pass an id or some other attribute of the user as a parameter to the action and send an invitation to that user.

Presumably you have a message or route for "users#invite"

(the action you wrote in your question). You can add the named parameter there, or you can pass the url parameter, or if you are using a post route, you can add the parameter to the body of the post.

Then in your contoller, you can do something like this (I will use email as an attribute):

def invite
  @user = User.find_by(email: params[:user_email])

  #Rails 3 like this
  # @user = User.find_by_email(params[:user_email])
   # now do stuff with user
end

      

+4


source


User.all will return a collection of users to you. So, Find user object to get id ... Try this code ....



def invite
     inviteUser = { 'user_id' => User.find_by_email('user@example.com').id, 'Magazine_id' => params[:id] }
     CollaborationInvitation.create(inviteUser)
     @magazine = Magazine.find(params[:id])
     redirect_to :back
     rescue ActionController::RedirectBackError
     redirect_to root_path
 end

      

+3


source


You may try

User.last.id

      

or

User.find_by_email("xyz@test.com").id

      

or

User.where(email: "xyz@test.com").first.id

      

Replace xyz@test.com with the desired user's email address. For more details on the active rail records interface check out the rail guides http://guides.rubyonrails.org/active_record_querying.html

+1


source







All Articles