Rails4 - How to design model to save multiple items for a table's column?

17 views
Skip to first unread message

Suresh Kumar

unread,
Nov 13, 2014, 5:34:51 AM11/13/14
to rubyonra...@googlegroups.com
I have a user model with name, email and password.
Now I want to add languages know by the user to the user model.

I can do that by the following

rails generate migration add_languagesknown_to_users
languagesknown:string

But I want the user to have the capability to store multiple languages.

Some users will know only one language some might know 10.



And,

I have a view to search all users when the search button is clicked. But
later I want to search users using languages known field. Can someone
kindly share on how do I create a migration for such use?



For instance, a user "Sam" signs up with English and Spanish as known
languages;
when users search for users who know English, Sam should be listed;
when users search for users who know Spanish, Sam should be listed.
How do I create a migration for this?



Should i create a table of languages and associate it with the user
model?

Can anybody share how please?

--
Posted via http://www.ruby-forum.com/.

James Davis, PhD

unread,
Nov 13, 2014, 8:09:57 AM11/13/14
to rubyonra...@googlegroups.com
For this situation, you should have User, Language, and UserLanguage models. User :has_many user_languages and :has_many languages :through user_languages.

Take a look at Ryan Bates' webcast http://railscasts.com/episodes/17-habtm-checkboxes-revised. It is a bit old but still applies to your question.

Reply all
Reply to author
Forward
0 new messages