【问题标题】:rails paperclip access image from another view轨道回形针从另一个视图访问图像
【发布时间】:2013-11-04 03:02:27
【问题描述】:

我的应用程序有一个 habtm 关系 b/w 列表和类别。现在从类别索引页面,用户过滤选择框以查看显示页面中的列表。

现在我无法访问附加到类别显示页面中列表的图像。

listing.rb

attr_accessible :placeholder, :categories_ids

  has_and_belongs_to_many :categories
  has_attached_file :placeholder, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png",
                      :url => "/system/:hash.:extension",
                     :hash_secret => "longSecretString"

类别控制器

def index
  @categories = Category.all
end

def show
  @categories = Category.find_by_sql ["select distinct l.* from listings l , categories c, categories_listings cl where c.id = cl.category_id and l.id = cl.listing_id and c.id in (?,?)" ,  params[:c][:id1] , params[:c][:id2]]
end

sql 只是过滤并显示显示页面中的列表,我可以在其中显示其属性,但无法访问占位符。注意 show 中的复数 @categories

分类显示页面

<ul>
  <% @categories.each_with_index do |c, index| %>
  <% if  index == 0 %>
    <li class="first"><%= c.place %></li>

    <%= image_tag c.placeholder.url(:thumb) %>

    <li><%= c.price %></li>

    <% else %>
    <li><%= c.place %></li>
    <li><%= c.price %></li>

    <%= image_tag c.placeholder.url(:thumb) %>
    <% end %>

  <% end %>
</ul>

Access image from different view in a view with paperclip gem ruby on rails

这表示使对象复数并调用循环,wch 应允许访问图像。

在这种情况下不起作用。

undefined method `placeholder' for #<Category:0x5c78640>

但令人惊奇的是,如果按照stackoverflow 中的建议使用,占位符将显示为所有列表的所有图像的数组,显然,wch 不是我喜欢的方式。问题出在哪里

【问题讨论】:

    标签: ruby-on-rails ruby paperclip


    【解决方案1】:

    因为类别没有方法占位符,而是有

    更新:

    @category.listings.each  do  |l| 
      l.placeholder
    end
    

    更新

    尝试获取类别,然后遍历其列表

    def show 
      @category = Category.find(params[:id]) #you get category and you able to loop throgh it listing array and get it placeholder
    end
    

    更新

    @categoies.each_with_index  do  |c| 
      c.listings.each do |l|
        l.placeholder
      end
    end
    

    更新2:

    @categoies.each_with_index  do  |c,i| 
      c.listings.each do |l|
        image_tag l.placeholder.url(:thumb)
      end
    end
    

    【讨论】:

    • 它不会工作。 @category 对象通过 sql 存储列表。我不能在 do 循环中使用 .listings。它抛出 nomethod 错误。
    • 列表的所有属性都可以以其当前形式访问。但无法访问占位符。它是列表中的一列。但是你呢?
    • 据我了解,在显示操作中,您希望显示属于类别和列表占位符的所有列表。我是赖吗?
    • 是的。那就是我正在尝试的。我可以显示所有列表及其属性,但不能显示占位符
    • 你为什么不直接使用@category = Category.find(params[:id])?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多