この投稿で多くのことを求めていることは承知していますが、Ruby/Rails に関する本を 4 冊読んだ後、「あはは」の瞬間が得られないという事実に不満を感じています。誰かが助けてくれるなら、私が来てあなたの朝食を作ります(1週間分)。
私は PHP/MySQL の世界から来ましたが、Rails の特定の事柄を理解するのが難しいと感じています。私が最後に読んだ Michael Hartl の本では、彼が本で作成したアプリケーションに追加する演習がいくつか提案されています。それは協会と関係があります。だから、私は本当に立ち往生しているので、誰かがこれについてのヒントを教えてくれるかどうか疑問に思っていました.
彼が構築するアプリケーションは、ほぼ Twitter のクローンです。マイクロポストを投稿するユーザーがいます。彼らのホームページは次のようになりますhttp://ruby.railstutorial.org/chapters/following-users#fig:home_page_with_feed ユーザー自身のマイクロポストは「フィード」の右側に投稿されます。フィード内のユーザーのマイクロポストに加えて、現在のユーザーがフォローしているユーザーによるマイクロポストもあります。任意のユーザーをフォローおよびフォロー解除できます。
この演習では、@replies を追加することを提案しています。@reply は、@username で始まるマイクロポストです (例: 「@mikeglaz お元気ですか」)。このマイクロポストは、あなたのフィードとユーザー名のフィードに表示されます (フォローしているユーザーとは限りません)。著者は次のように提案しています: 「これには、microposts テーブルに in_reply_to 列を追加し、Micropost モデルに追加の includes_replies スコープを追加する必要があるかもしれません。」しかし、他のユーザーをフォローすることに関する関連付けは非常に複雑で、これが私を行き詰まらせている原因です。私はいくつかのコードを投稿します:
ユーザー
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
has_many :microposts, dependent: :destroy
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
def feed
Micropost.from_users_followed_by(self)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy
end
end
end
関係
class Relationship < ActiveRecord::Base
attr_accessible :followed_id
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
end
マイクロポスト
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
def self.from_users_followed_by(user)
followed_user_ids = user.followed_user_ids
where("user_id IN (?) OR user_id = ?", followed_user_ids, user)
end
end