私はユーザとプロジェクトの間のアソシエーションを作成して、ユーザがプロジェクトに参加できるようにしました。アソシエーションテーブルは存在しますが、どのようにアソシエーションを作成するのかは不明です。Rails 4 - has_and_belongs_to_manyのアロケーション
答えて
あなたのプロジェクトのIDが内部に隠されていますので、あなたが@projectとインスタンスのインスタンスを持っている場合は、ちょうどそう、この内部は、JOIN(ポスト)アクション
def join
@project = Project.find(params[:project][:id])
current_user.projects << @project
end
を行うことができます私の例ではcurrent_userです(例えばdeviseを使用している場合など)。オペレータを使用して割り当てます。< <
ここは参照です:
http://guides.rubyonrails.org/association_basics.html#has-many-association-reference
ので検証、あなたがコールバックに行うための方法がないので、私は間違いなく、にない使用has_and_belongs_to_many
あなたをお勧めしなければならないことが
お返事ありがとうございます。グループに参加したユーザーをどのように表示するのですか? –
ちょっと分かりましたありがとうございました!私はまだupvoteを傾ける... –
を役に立てば幸いし、に。
実際の結合モデルを使用してhas_many, through
を使用するのは間違いなく良いです。
class User
has_many :project_users, dependent: :destroy
has_many :projects, through: :project_users
end
class Project
has_many :project_users, dependent: :destroy
has_many :users, through: :project_users
end
class ProjectUser
belongs_to :project, required: true
belongs_to :user, required: true
validates :project, uniqueness: { scope: :user }
end
これは非常にシームレスに動作し、あなたが行うことができます:
User.update(project_ids: [1,5,6,7])
し、任意の検証が失敗しない限り、それはこれらのプロジェクトにユーザーを参加しますが。
私は数ヶ月後に私たちが重複の問題、レコードの悪い状態に陥り始めた後、これらのテーブルで大きなプロジェクトを開始しました。実際の結合モデルを使用することはその価値があります。
ヒントをありがとう!それを心に留めてください! –
- 1. Railsのhas_and_belongs_to_many
- 2. Rails 3 - has_and_belongs_to_many
- 3. Rails has_and_belongs_to_many migration
- 4. Has_and_belongs_to_many in Rails 3
- 5. Ruby on Rails - has_and_belongs_to_many relationship
- 6. has_many:through with has_and_belongs_to_many in Rails
- 7. Rails has_and_belongs_to_many他のクエリとの関連
- 8. Railsの多型的なアロケーションでのクエリのDRYup
- 9. has_and_belongs_to_manyバリデーション
- 10. has_and_belongs_to_manyのSearchkick集計
- 11. has_and_belongs_to_manyの問題でのRailsの機能テスト
- 12. レールhas_and_belongs_to_manyアソシエーション
- 13. Railsのサーバーエラー - Railsの4
- 14. Rails/Active Record has_and_belongs_to_many association - レコードを取得する
- 15. Rails 3.1 - has_and_belongs_to_manyは推奨されていませんか?
- 16. Railsについて混乱していますhas_and_belongs_to_many Association
- 17. Railsの4 - will_paginate
- 18. Railsの4 - eager_load
- 19. レコード - Railsの4
- 20. cancancan has_and_belongs_to_manyの能力
- 21. Mongoid has_and_belongs_to_many associations
- 22. ra_s_soft_deletable with has_and_belongs_to_many
- 23. Has_and_belongs_to_manyと単一テーブル継承
- 24. iphoneアプリのスタートアップシャットダウンのアロケーション時間
- 25. cygwin/dev/sd *ディスクのハードドライブへのアロケーション
- 26. Railsの4 - HTMLスタイリング
- 27. Railsの4エラー:URL
- 28. Railsの4:fields_for fields_for
- 29. jquery_datepickerはRailsの4
- 30. Rails 4:SubDomainsのユーザログイン
ここでの質問は、hasとmany associationに属するプロジェクトにユーザーを援助するコードを書く方法です。 –
はい!どこで始めるべきなのかわからないT_T –