1

How can I get data from an array of the form:

[#<User id: 1, name: "John", surname: "Smith", dob: "2016-07-26", location: "Liverpool", created_at: "2016-07-26 08:50:01", updated_at: "2016-07-26 08:50:01">]

generated from sqlite3 database using this code:

<%= User.select(User.all.select { |u| u.id == 1 }) %>

Also, is there any better way to extract selected fields than everything? Whatever I tried returns some long random numbers like references.

And finally, how can I make the:

u.id == 1

to become any id given to that user in real time, like the following:

u.id == x (where x is any number)

Cheers!

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
hack-is-art
  • 325
  • 5
  • 20
  • to select a specific field from a database set, you can use `pluck` – Kkulikovskis Jul 26 '16 at 10:13
  • i tried <%= User.find(1).name %> and it works, but I want a function to make this automatically by passing the id of the user who just register and return its name to the screen – hack-is-art Jul 26 '16 at 10:55
  • well, then you can just use `User.last.name` if the you want to show the name right after registration (though it is not safe if two people register at the same time. Another way is to pass the registered user as an instance variable. Surely you have a controller method where you have `@user.save` or something similar. So then just display '@user.name` in your view – Kkulikovskis Jul 26 '16 at 13:25

1 Answers1

1

I don't know if I'm missing something but I think what you want is either find:

@user = User.find(x) # x = given id

or where (returns a set of users, not just one)

@user = User.where(id: x)

And then in your view you can use the user like this:

<%= @user.name %> 
siegy22
  • 4,295
  • 3
  • 25
  • 43
  • I have the following code in my users_controller: def show @user = User.find(params[:id]) end because of the warning i am getting in the view file that find or find_by should not be used inside a view. BUT when I write User.show I am getting an error "No Method Error" and I don't know why. – hack-is-art Jul 26 '16 at 10:15
  • What? I edited the question. see how to use it. If you load it in your controller, you don't need to load it again in your view. – siegy22 Jul 26 '16 at 10:19
  • In real time, when a user just registers to my app, how can I give back the actual name he gave using the id, like User.find(1).name, but the id will not be and it will be something generated at that time. I accept your answer as the 'ticked' one but please help me on the question i just made. – hack-is-art Jul 26 '16 at 10:21
  • i tried <%= User.find(1).name %> and it works, but I want the registered user to have this and i want to make it automatic – hack-is-art Jul 26 '16 at 10:28