So, I’ve got two models: User and Group.
User belongs_to :group
and
Group has_many :users.
When creating a new User, I want to check for an already created Group and assign them, or create a new Group based on user-supplied information. Group.find_or_create_by_name("Name") seems like a great way to do this, but my question is where should this be located? I’m guessing that following “Fat Models, skinny Controllers” it should be in user.rb. If it’s in the model, what is the best way to pass in user-supplied strings on user creation? Should I set up a method in user.rb and then call that method in users_controller.rb?
And I guess a related question: I know that my schema should reflect
create_table "users" do |t|
t.integer "group_id"
for the purpose of querying. How exactly does Rails “automagically” link these? When creating my Group model, I’m guessing it needs to have a string:id column, and Rails just links the two?
Sorry for my obvious lack of understanding on associations, but I’m trying not to just hack something together that works awkwardly, and want to make sure I understand the best way to go about it.
First of all, according to what you wrote, a group can have multiple users in it, but a user can only be part of a single group.
Usually, a group can have multiple members and a user can be member of multiple groups. To achieve that, you create an association model, called
membership.So, your user model have :
And your group model have :
The association will have a table on it’s own that will be something like :
To answer your original question, if you have to create a group when a user is created regardless of the way he is created, I would create an Active Record Callback in the user model :
For more information about Active Record Callbacks, see http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
If the group you are creating is related to the information entered in a form (view) and is not directly related to the user, then you would have to do the creation of the group in the controller. Something like :
Or, cleaner way :