【问题标题】:Ruby on Rails - Paperclip getting ImageRuby on Rails - 回形针获取图像
【发布时间】:2012-05-17 15:30:14
【问题描述】:

我正在使用 Paperclip 处理将照片上传到我的应用程序,但在检索它们时遇到了一些问题

我可以成功添加/删除/显示所有图像,但我怎样才能只检索我的模特的一张照片?比如第一个?

要全部检索它们,我正在使用:

<%= form_for @hotel, :html => {:multipart => true} do |f| %>
  <%= f.fields_for :hphotos do |hp|%>
     <%= image_tag(hp.object.hphoto.url(:medium))%>
  <%end%>
<%end%>

效果很好,但在我的索引中,我只想为每个显示的酒店显示一张照片。 我得到了:

undefined method `Hphotos'
I also ran across: undefined method `url' when testing

我怀疑问题出在我的控制器上,但我不确定是什么问题,就在这里(我也在执行创建操作,效果很好)

 def index

   @hotels= Hotel.search(params)
   @hotels= <pagination>
#I think the issue is here
   @hotels.Hphotos.build #changing to @hotels.Hphoto.build or @hotels.hphotos.build won't work and I think my issue is here.
    respond_to do |format|
      format.html 
      format.json { render :json => @hotels }
    end
  end

这很好用:

def new
    @hotel = Hotel.new
    2.times { @hotel.hphotos.build }
end

我在我的索引视图上这样做:

<% @hotels.each do |hotel|%>
(...)
<%= image_tag hotel.hphoto.url(:small) %>
(...)
<%end%>

就像我说的,我只想检索第一张图片,但即使在索引中我也无法全部获取,所以我认为问题出在控制器上。

感谢阅读,欢迎任何提示,我有点卡住了:)

问候

【问题讨论】:

    标签: ruby-on-rails image controller paperclip


    【解决方案1】:

    在您的索引视图中,您调用的是 hotel.hphoto,但它应该是 hphotos,因为它是一对多的关系。如果你想要第一个,你应该这样做:

    hotel.hphotos.first.url(:small)
    

    【讨论】:

    • 我收到了undefined method url。有什么想法吗?
    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 2014-11-25
    • 2013-04-15
    • 2017-01-14
    • 1970-01-01
    • 2015-11-14
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多