Lotix
Lotix

Reputation: 309

Multiple values for one column field in Rails

How do i create a column which stores multiple values for a User model in Rails app?

Example:

I want to have a User model and store multiple fruit preferences. What type of fruit_preference would i need to add in order to store multiple fruit_preference values? Such as: fruit_preference: apple, orange, pear

I want to find specific users based on one of those fruits in my app later on.

Upvotes: 2

Views: 2569

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

Answering the original question - array data type.

But what you really need is associations.

class User
 has_many :fruits
end

class Fruit
  belongs_to :user
end

Having such setup you will be able to query users to find those with specific fruit:

User.joins(:fruits).where(fruits: {name: 'apple'})

As well, as having all user's fruits (because he can have multiple):

User.first.fruits
#=> collection of Fruit objects

This is way better, that storing user's fruits as a collection in database, because pretty quick maintaining/changing/updating these collections becomes hard.

Upvotes: 3

Related Questions