【问题标题】:Ruby on Rails: proper use of image_tag with carrierwave on a nested modelRuby on Rails:在嵌套模型上正确使用 image_tag 和carrierwave
【发布时间】:2012-10-23 00:33:53
【问题描述】:

我有部分命名为 _userbox,它显示从用户模型中抓取的数据。我还有一个单独的图像模型,它存储有关图像的信息。

class User
  ...
  has_many :images, :dependent => :destroy  
  accepts_nested_attributes_for :images, allow_destroy: true    
  ...
end

class Image
  ...
  attr_accessible :image_priority, :image_title, :image_location
  belongs_to :user
  mount_uploader :image_location, ProfilePictureUploader
  ...
end

_userbox.html.erb
    <% @users.each do |user| %>     
      <tr>
        <td><%= image_tag user.images.image_location.url.to_s %></td>
        <td valign="top">
          <p><%= link_to user.first_name, user_path(user) %></p>
          <p><%= age(user.date_of_birth) %> / <%= user.gender %> / <%= user.orientation %></p>
          <p>from <%= user.location %></p>
          <p>Question? Answer answer answer answer answer answer answer</p>
        </td>
      </tr>
    <% end %>

它工作正常,除了 image_tag。我正在使用carrierwave gem 上传图像文件。文件已上传,但我不知道在我看来访问它们的正确方法是什么。 我收到如下错误消息: []:ActiveRecord::Relation 的未定义方法 `image_location'

使用该 image_tag 的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails carrierwave nested-attributes


    【解决方案1】:

    您有has_many :images,所以user.images 是一个关系,而不是单个Image 实例。要在您的部分中显示某些内容,请显示第一张图像,或者循环它们:

    <% @users.each do |user| %>     
      <tr>
        <td><%= image_tag user.images.first.image_location.url.to_s %></td>
        <td valign="top">... 
        </td>
      </tr>
    <% end %>
    

    或循环遍历它们:

    <% @users.each do |user| %>     
      <tr>
        <td>
          <% user.images.each do |img| %>
            <%= image_tag img.image_location.url.to_s %>
          <% end %>
        </td>
        <td valign="top">... 
        </td>
      </tr>
    <% end %>
    

    【讨论】:

    • 非常感谢。所以假设我只想显示具有 image_priority == 1 的图像(总是有一个具有该优先级的图像),我是否仍然需要遍历所有图像,或者有没有办法从数据库中选择这种数据?跨度>
    • 您可以在 Relation 实例上使用所有标准方法(例如 .where(...) )。
    • 谢谢!这很有帮助
    猜你喜欢
    • 1970-01-01
    • 2014-07-15
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多