开发者

Rails adding resource id to another resource via HABTM

I have 3 pertinent models:

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

class Group开发者_如何学Go < ActiveRecord::Base
    has_and_belongs_to_many :users
has_many :galleries
end

class Gallery < ActiveRecord::Base
    belongs_to :group
end

I want to be able to create users and galleries within a group so that only users who are members of the group can view the galleries that belong to that group. I also want users to be able to view galleries of other groups they belong to (hence the HABTM association).

I'm having difficulty in conceptualizing how this works with controllers, and perhaps I'm over thinking the problem. If I create a Group, and then I go to create a user, what is the best way to go about adding the current group_id to the user model? Same thing goes for the gallery model...

Does that make sense?

Let me know if I need to clarify or add code samples.

Thank you very much for your help.

EDIT: Clarification I definitely didn't make any sense in my initial question, but I did manage to find the answer, with help from a friend.

What I ended up doing is passing the group_id to the form via the params hash like so:

<%= link_to "Add User", new_admin_user_path(:group_id => @group.id) %>
<%= link_to "Add Gallery", new_gallery_path(:group_id => @group.id) %>

Then using a hidden field in my form, assigning the group_id to the "group_id" hidden field:

<%= hidden_field_tag :group_id, params[:group_id] %>

And, finally, in my create methods, adding these lines before the save assigns the group_id perfectly:

# Gallery only has one group
@gallery.group_id = params[:group_id]
# Users can belong to many groups
@user.groups << Group.find(params[:group_id])

I'll still need to sit down and wrap my head around the answers you both provided. Thank you very much for taking the time to help me out. I really appreciate it.


When you are using find method from your controller you can make it like this:

Gallery.find :all, :joins => "INNER JOIN groups ON groups.gallery_id = galleries.id INNER JOIN users ON users.group_id = groups.id", :conditions => "users.id = #{@your_current_user_id}"

It must find all galleries of groups which the user belongs.


I would not define this in the controller as Sebes suggests, but rather in the User model.

Adapting his idea:

def galleries
  Gallery.joins(:groups => :users).where("users.id = ?", self.id)
end

Then to get a collection of the galleries for the current_user object:

current_user.galleries
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜