0

has_and_belongs_to_many 関係を実装してみてください 1 つのドキュメントには多くのグループがあります 1 つのグループには多くのドキュメントがあります

結合テーブル呼び出しの documents_group が作成されました

モデル

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

モデル 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

移行は

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

    end

グループに対応するすべてのドキュメントにアクセスしたい

4

1 に答える 1

2

#documentsグループのすべてのドキュメントにアクセスするには、特定のグループモデルを呼び出すだけです。例えば:

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

ただし、新しいドキュメントをグループに割り当てていないように見えるため、問題が発生する可能性があります。あなたはそれをいくつかの方法で行うことができます、1つの可能な方法は前@document.saveに以下を追加するDocumentsController#createことです(あなたがという名前のパラメータを持っていると仮定してgroup_id

@document.group = Group.find(params[:group_id]) 
于 2012-05-11T05:11:55.837 に答える