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!

3
  • to select a specific field from a database set, you can use pluck Commented Jul 26, 2016 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 Commented Jul 26, 2016 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 Commented Jul 26, 2016 at 13:25

1 Answer 1

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 %> 
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.