【发布时间】:2015-08-03 18:51:53
【问题描述】:
我知道我在这篇文章中提出了很多要求,但是在阅读了 4 本书关于 Ruby/Rails 之后,我对我没有得到“啊哈”时刻感到沮丧。如果有人可以帮忙,我会过来给你做早餐(一个星期)。
我来自 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 模型添加一个额外的 include_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
【问题讨论】:
标签: ruby-on-rails-3 railstutorial.org