我知道我在这篇文章中要求很多,但是在阅读了4本有关Ruby/Rails的书籍之后,我感到沮丧的是我没有得到“aha”时刻。如果有人能帮忙,我会过来给你煮早餐(一周)。Ruby on Rails 3教程练习no。 1提示
我来自PHP/MySQL的世界,我发现很难在Rails中掌握某些东西。 Michael Hartl读过的最后一本书提出了一些练习,以增加他在书中构建的应用程序。它与社团有关。所以我想知道如果有人可以给我一些提示如何去做这件事,因为我真的被卡住了。
他构建的应用程序几乎是一个Twitter克隆。有发布Microposts的用户。他们的主页看起来像这样http://ruby.railstutorial.org/chapters/following-users#fig:home_page_with_feed用户自己的Microposts被放在'feed'的右边。与Feed中用户的Microposts一起的还有当前用户所遵循的用户Microposts。您可以关注并取消关注您想要的任何用户。
该练习建议添加@replies。 @reply是以@username开头的Micropost(例如'@mikeglaz你好吗')。此Micropost将出现在您的Feed和用户名的Feed中(不一定是您关注的人)。作者提出以下建议:'这可能涉及在microposts表中添加in_reply_to列,并向Micropost模型中添加一个包含范围的范围。'但关于跟随其他用户的联系非常复杂,这就是让我陷入困境的原因。我会后一些代码:
用户
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
我感谢你的帮助@bento。 – mikeglaz 2012-07-30 22:30:30