Hi
I’m working on a project that has users and groups, users can be members of a group or they can just be a user - what’s going to be the best way to deal with this?
I understand the normal has_many relationship just not sure how to do this one. Will try to post some code snippets tomorrow.
Thanks, Cameron
has_many :through seems perfect for this, given the many-to-many
nature and the possibility you'll want to have additional info about
the relationship (like when they joined, positions held within the
group, etc.).
-Dave
If the user can only be a member of one group then use User belongs_to
group. If a particular member does not belong to a group then just
leave group_id nil. You will obviously have to allow for user.group
== nil in the code where appropriate. If he can belong to many (or
no) groups then use has_many :through as Dave suggested. You can test
user.groups to see if he is in any groups.
Oh, good point. I was assuming (and you know what happens then!) that
a User could belong to many Groups.
-Dave
Thanks Dave & Colin! That was how I had hoped it would work!
Here is an update, I have it working as only a group or as only a non-group user. I have below the create controller and was wondering what would be the best way to allow associations and non-associated records. Thanks
def create
if Group.nil?
@group = Group.find(params[:group_id])
@user = @group.users.create(params[:user])
else
@user = User.new
@user.ip_address = request.remote_ip
@user.ua_string = request.user_agent
@user = User.new(params[:user])
end
respond_to do |format|
if @user.save && @user.group_id == nil
format.html { redirect_to “/”, notice: ‘Thank you for registering!’ }
elsif @user.save && @user.group_id != “”
format.html { redirect_to group_path(@group.token), notice: ‘Thank you for registering!’ }
else
format.html { render action: “new” }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
This will do (or at least try) the save twice, if the user has a
group. I'd recommend:
if it saves
redirect to (if it has a group, the group, else /)
else
give error msg
end
Also, look closely at the way you're checking for a group. The first
option will trigger if the group is nil, the second if it's not ""
(empty string)... but what if it *is* ""? That's neither nil nor
not-"", so it will take the "else" path and pretend like it didn't
save. I suggest you use .blank? (or its inverse, .present?) to tell
if it's there or not. Both nil and "" count as blank (and not
present).
-Dave
Here is an update, I have it working as only a group or as only a non-group
user. I have below the create controller and was wondering what would be the
best way to allow associations and non-associated records. Thanks
def create
if Group.nil?
Can you explain what the above line is for?
Colin