Muhambi
Muhambi

Reputation: 3522

Make array out of User ids

I'm using devise and a custom controller in Rails.

In a controller, I have:

def new
  @users = Users.where(store_id: 5)
  @array_of_users = []
end

In a view I have:

<%= f.hidden_field :employees, value: @users %>

Basically, I just want to get the employee ids and store them into an array, so if we have a user with id=50 and another with id=56, then store [50,56] in the hidden field. How can I do this?

Upvotes: 0

Views: 61

Answers (2)

Vince V.
Vince V.

Reputation: 3143

Just select the user ids directly from the database, it will return an array. If you convert the array into a string you will get something like this: [1,5,6,7]

def new
  @users = User.where(:store_id, 5).select("id")
end

<%= f.hidden_field :employees, value: @users.to_s %>

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

Use this :

def new
  @users = Users.where(store_id: 5)
  @user_ids = @users.pluck(:id)
  @array_of_users = [] # no ides what is this for, so kept as it is.
end

Then inside the views :

<%= f.hidden_field :employees, :multiple => true, value: @user_ids %>

Upvotes: 1

Related Questions