[英]Ruby on Rails: proper use of image_tag with carrierwave on a nested model
I have partial named _userbox, which displays data grabbed from the user model. 我有部分名为_userbox,它显示从用户模型中获取的数据。 I also have a seperate image model, which stores information about images. 我还有一个单独的图像模型,它存储有关图像的信息。
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 %>
It works fine, except image_tag. 它工作正常,除了image_tag。 I'm using the carrierwave gem to upload image files. 我正在使用carrierwave gem上传图像文件。 The files are uploaded, but I don't know what is the proper way to acesss them in my view. 文件已上传,但我不知道在我的视图中访问它们的正确方法是什么。 I get error message like: undefined method `image_location' for []:ActiveRecord::Relation 我收到错误消息,如:[]:ActiveRecord :: Relation的未定义方法`image_location'
What is the proper way to use that image_tag? 使用该image_tag的正确方法是什么?
You have has_many :images
, so user.images
is a relation, not a single Image
instance. 你有has_many :images
,所以user.images
是一个关系,而不是一个Image
实例。 To show something in your partial, either show the first image, or loop over them: 要显示部分内容,请显示第一个图像,或者循环显示它们:
<% @users.each do |user| %>
<tr>
<td><%= image_tag user.images.first.image_location.url.to_s %></td>
<td valign="top">...
</td>
</tr>
<% end %>
or loop over them: 或者循环遍历它们:
<% @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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.