【问题标题】:Displaying pic for user through a question's answer通过问题的答案为用户显示图片
【发布时间】:2010-05-25 04:54:31
【问题描述】:

好的,我正在尝试显示用户的个人资料图片。我设置的应用程序允许用户创建问题和答案(我在代码中将答案称为“站点”)我试图这样做的视图位于/views/questions/show.html.erb 文件中。值得注意的是,我正在使用 Paperclip gem。设置如下:

协会

Users

class User < ActiveRecord::Base

  has_many :questions, :dependent => :destroy
  has_many :sites, :dependent => :destroy
  has_many :notes, :dependent => :destroy
  has_many :likes, :through => :sites , :dependent => :destroy
  has_many :pics, :dependent => :destroy
  has_many :likes, :dependent => :destroy


end

问题

class Question < ActiveRecord::Base
  has_many :sites, :dependent => :destroy
  has_many :notes, :dependent => :destroy
  has_many :likes, :dependent => :destroy
  belongs_to :user
 end

答案(网站)

class Site < ActiveRecord::Base

  belongs_to :question
  belongs_to :user
  has_many :notes, :dependent => :destroy
  has_many :likes, :dependent => :destroy

  has_attached_file :photo, :styles => { :small => "250x250>" }
end

图片

class Pic < ActiveRecord::Base
  has_attached_file :profile_pic, :styles => { :small => "100x100" }
  belongs_to :user
end

/views/questions/show.html.erb 正在渲染部分 /views/sites/_site.html.erb,它通过以下方式调用答案(站点):

<% div_for site do %>
<%=h site.description %>
<% end %>

我一直在尝试做以下事情:

<%=image_tag site.user.pic.profile_pic.url(:small) %>
<%=image_tag site.user.profile_pic.url(:small) %>

等等。但这显然是错误的。我的错误将我引导至 Questions#show 操作,因此我想象我需要在其中定义一些东西,但不确定是什么。是否可以根据当前关联、调用位置以及如果需要添加什么控制器以及哪一行代码将调用图片来调用图片?

更新:这里是 QuestionsController#show 代码:

  def show

    @question = Question.find(params[:id])
    @sites = @question.sites.all(:select => "sites.*, SUM(likes.like) as like_total",
             :joins => "LEFT JOIN likes AS likes ON likes.site_id = sites.id",
             :group => "sites.id",
             :order => "like_total DESC")

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @question }
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby associations paperclip


    【解决方案1】:

    你有has_many图片关联:

    class User < ActiveRecord::Base
      ...
      has_many :pics, :dependent => :destroy
    end
    

    但你却试图表现得好像只有一张照片:

    <%=image_tag site.user.pic.profile_pic.url(:small) %>
    

    所以要么拍第一张照片(可能你还应该检查它是否存在):

    <%=image_tag site.user.pics.first.profile_pic.url(:small) %>
    

    如果用户只能拥有一张图片,则将关联更改为has_one:

    class User < ActiveRecord::Base
      ...
      has_one :pic, :dependent => :destroy
    end
    
    <%=image_tag site.user.pic.profile_pic.url(:small) %>
    

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多