0

私はステータスを作成するユーザとステータスがあるユーザを持つステータスを作成しようとしています。ruby​​アソシエーションと同じクラスにhas_oneとbelongs_toを使用する

Facebookの投稿に誰かを「タグ付け」するのと非常によく似ています。投稿を作成したユーザーが所有者になる必要がありますが、ステータスが実際のステータスと関連するユーザーを関連付ける方法を理解する必要もあります。

最終目標は、特定のユーザーに関するすべてのステータスを表示することです。

私はステータスクラスを持っています。

class Status < ApplicationRecord 
    belongs_to :user 

    validates :content, presence: true, 
         length: { minimum: 2} 

    validates :user_id, presence: true 
end 

私はまた、ユーザークラス私はもともと私の状態クラスに

has_one :user 

を追加するために考え

class User < ApplicationRecord 
    rolify 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    validates :first_name, presence: true 

    validates :last_name, presence: true 

    validates :profile_name, presence: true, uniqueness: true, 
          format: { 
          with: /\A[a-zA-Z0-9_-]+\z/, 
          message: 'Must be formatted correctly' 
          } 

    has_many :statuses 
end 

を持っていますが、私は今、これが最適な実装することができないことを実現しています。

誰でもこの関連付けを教えてもらえますか?

答えて

0

この場合、ユーザーは多くのステータスを持つことができ、ステータスには多くのユーザー(作成したユーザー、ステータスのタグ付きユーザー)が存在する可能性があるため、それを正しく理解する)。

ステータスとユーザーの間にモデルを作成し、Status_Infoと呼び、作成者またはタグ付けされた人物のレコードが作成されたかどうかを示すinfo属性を作成することをお勧めします。

ユーザーに関するすべてのステータスを検索するには、Status_Infoモデルでそのuser_idを検索するだけです。すなわち、Status_Info.where(user_id:wanted_user_id)

4

ユーザーは複数のステータスを作成し、複数のユーザーに1つのステータスでタグを付けることができなければなりません。したがって、has_oneではなくhas_manyを使用する必要があります。同じクラスで複数の関連付けを作成するためとして

class Status < ApplicationRecord 
    belongs_to :creator, class_name: 'User', foreign_key: 'creator_id' 
    has_many :referred_users, through: :mentions, source: :user 
end 

class Mention < ApplicationRecord 
    belongs_to :status 
    belongs_to :user 
end 

class User < ApplicationRecord 
    has_many :statuses, foreign_key: 'creator_id' 
    has_many :referring_statuses, through: :mentions, source: :status 
end 
+0

は通じテーブルが必要とされていると言って答えを投稿してちょうど約だったが、あなたの編集は、前の回答で問題が修正されているように。私はちょうどupvoteと一緒に移動します;) –

+0

@ JohnHayesリード、まあ、私は彼が多くの多くを必要とし、何らかの理由で私はそれをしていないと言いました。ここ4:30 AMです:) – ndn

関連する問題