Swagata Mondal
Swagata Mondal

Reputation: 51

how to access data in habtm relationship

try to implement has_and_belongs_to_many relationship one documents has many group one group has many documents

a join table call documents_group created

Model

class Group < ActiveRecord::Base
  has_many :users
  has_and_belongs_to_many :documents
end

Model 2

class Documents < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :groups
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
  before_post_process :resize_images

  def image?
    avatar_content_type =~ %r{^(image|(x-)?application)/(bmp|gif|jpeg|jpg|pjpeg|png|x-png)$}
  end

private

  def resize_images
    return false unless image?
  end
end

controller create def create @document = Documents.all

 @document = Documents.create( params[:document] )

 @document.user_id = current_user.id
 @document.save
 redirect_to root_path
 end

migration is

     def self.up
     create_table :documents_groups ,:id => false do |t|
      t.integer :documents_id
      t.integer :group_id
     end

    end

now i want to acess all documents coreespond to a group how to do

Upvotes: 0

Views: 964

Answers (1)

Colin R
Colin R

Reputation: 17751

To access all the documents of a group, just call #documents on the specific group model. For example:

Group.find(params[:id]).documents #=> Collection of groups documents as Array

You might run into a problem though because it looks like you're never assigning the new document to a group. You can do that several ways, one possible way is adding the following before @document.save in DocumentsController#create (assuming you have a parameter named group_id)

@document.group = Group.find(params[:group_id]) 

Upvotes: 2

Related Questions