Reputation: 2662
I have user model
and Language model
where the language model contains different languages and i want the user to select the languages from that model and it should be stored for the corresponding user. Consider there are five languages A, B, C, D, E
then the user has to select from the languages. Suppose user 1
selects A and C
whereas user 2
selects B and D
then the languages has to be stored for that user. How can i do this? please help me.
Upvotes: 0
Views: 70
Reputation: 3681
You can do it through association,in your case you can try like:
class User < ActiveRecord::Base
has_and_belongs_to_many :languages
end
and
class Language < ActiveRecord::Base
has_and_belongs_to_many :users
end
or may be you can go through with the following links.
http://guides.rubyonrails.org/association_basics.html
http://www.tutorialspoint.com/ruby-on-rails/rails-models.htm
Upvotes: 1
Reputation: 8892
You need to model a many-to-many relationship. As explained in the link, this can be done by declaring
class User < ActiveRecord::Base
has_and_belongs_to_many :languages
end
class Language < ActiveRecord::Base
has_and_belongs_to_many :users
end
and creating a new table called something like language_users
to store user_id
and language_id
. Each record in this table indicates that a particular user has selected a particular language.
Upvotes: 1