Execution environment
  • Rails
  • Vue.js 2.6.1
What i am doing

I'm using Vue.js in Rails to create a component that displays information about the logged-in user. (The image is a reference image)

When passing data from Rails to Vue.js side, data is passed from the controller as follows.

class Api :: ApplicationController</pre>
<strong>I want to solve</strong>
<p>But with the above method<code>/ api/current_user</code>When accessing (routing has been adjusted slightly), user information is displayed in the following form.</p>
<pre><code>{"id": 3,
"name": "Test User",
"email": "[email protected]",
"password_digest": "$2a $12 $DEHHl/czPM7pIBVK/4A1mulOKcB/msTSPDnMUqBmLEMSDI50v5/Vq",
(... omitted),
"created_at": "2020-10-09T17: 12: 40.268 + 09: 00",
"updated_at": "2020-10-09T17: 12: 40.268 + 09: 00"}

Since there is a lot of raw information, I want to limit the information displayed.

What I tried

For information on multiple usersselectI understand that the method can retrieve only specific columns.

$rails c
$users = User.all
$users.select (: name,: email)
# =>[#<User: 0x00007fe6eb1529d8
# id: nil,
# name: "Test User 1",
# email: "[email protected]">,
##<User: 0x00007fe6eb1527f8
# id: nil,
# name: "Test User 2",
# email: "[email protected]">,
# (Omitted ...)]

I don't know how to retrieve only a specific column when there is only one user.dig,pluckI'm trying the method I came up with. If i know a good way, I would be grateful if you could tell me.


On the Vue.js sideuser ['name']I want to retrieve the data in the form of, so if possible, I want to retrieve the data in the form of key and value.

Api :: ApplicationControllerI would like to add a redirect setting to.

I thought about writing a method to put the necessary information into the array one by one, but I posted a question because I wanted a simpler method.

  • Answer # 1

    How about using jbuilder etc. to assemble JSON with only the necessary information?

  • Answer # 2

    current_user.attributes.slice ('name','email')


    current_user.slice (: name,: email)

    It seems that slice can be used directly on the instance.

  • Answer # 3

    to_jsonThen you can narrow down the columns when converting to JSON.

    render current_user.to_json (: name)

    I think it is also possible to do something like this.

Related articles