2012-10-23 64 views
0

我有部分名为_userbox,它显示从用户模型中获取的数据。我也有一个单独的图像模型,它存储有关图像的信息。Ruby on Rails:在嵌套模型上正确使用image_tag和carrierwave

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。我正在使用载波宝石上传图像文件。这些文件已上传,但我不知道在我看来什么是正确的接入方式。 我得到如下错误消息: 未定义的方法`image_location'for []:ActiveRecord ::关系

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

回答

2

你有has_many :images,所以user.images是一个关系,而不是一个单一的Image实例。要显示在您的局部的东西,无论是显示第1图像,或环比他们:

<% @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 %> 
+0

非常感谢你。因此,假设我只想显示image_priority == 1的图像(总是有一个图像具有该优先级),还是必须遍历所有图像,或者有没有办法从数据库中选择这种数据? – TimmyOnRails

+0

您可以在“关系”实例上使用所有标准方法(例如'.where(...)')。 – rewritten

+0

谢谢!这非常有帮助 – TimmyOnRails