如何在Rails

时间:2017-01-22 14:09:53

标签: ruby-on-rails paperclip avatar

所有,我目前正在学习Rails并继续进行项目,我遇到了一个问题。我无法显示帖子所属的用户的图像。

当我进入主页时,我应该看到你关注的用户的帖子...不幸的是我不知道我怎么能显示帖子所属的用户的形象....我可以显示他们的帖子,但不知道我如何显示他们的形象。我必须说我正在使用paperclip gem。

用户模型

class User < ActiveRecord::Base

#包括默认设计模块。其他可用的是:   #:确认,:可锁定,:超时和:omniauthable   设计:database_authenticatable,:registerable,          :可恢复,:可记住,:可跟踪,:可验证          has_attached_file:avatar,:styles =&gt; {:medium =&gt; “300x300&gt;”,:thumb =&gt; “100x100#”} ,: default_url =&gt; “/images/:style/missing.png”          validates_attachment_content_type:avatar,:content_type =&gt; / \ Aimage /.* \ Z /

     has_many :followeds, through: :relationships
      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"
     has_many :reverse_relationships, foreign_key: "followed_id",
                               class_name:  "Relationship",
                               dependent:   :destroy
     has_many :followers, through: :reverse_relationships, source: :follower


     has_many:avatar, dependent: :destroy
     has_many :posts, dependent: :destroy # remove a user's posts if his account is deleted.
     has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
     has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy

     has_many :following, through: :active_relationships, source: :followed
     has_many :followers, through: :passive_relationships, source: :follower




    def avatar_url
    avatar.url(:medium)
    end

     # helper methods

     # follow another user
     def follow(other)
       active_relationships.create(followed_id: other.id)
     end

     # unfollow a user
     def unfollow(other)
       active_relationships.find_by(followed_id: other.id).destroy
     end

     # is following a user?
     def following?(other)
       following.include?(other)

     end
     end

我可以获得当前的用户图片,但如果我登录我的帐户,并且我关注某人,我希望他们的相关帖子看到他们的图片不是我的...

             <%=image_tag(current_user.avatar.url, class: "img-circle img-responsive img-raised", :size => "100x100") %>

1 个答案:

答案 0 :(得分:0)

您的帖子必须在数据库中有belongs_to :useruser_id,然后您可以这样做:

@posts.each do |post|
  <%=image_tag(post.user.avatar.url, class: "img-circle img-responsive img-raised", :size => "100x100") %>
end

但我发现你有has_many :avatar这里发布的代码可能有误,如果不是,你必须先选择你想要使用的avatar_url。