简体   繁体   English

使用图片ID的Rails回形针图片网址?

[英]Rails Paperclip image URL using Image ID?

Well I'm stuck again. 好吧,我再次陷入困境。 And this time, maybe it's because I'm using a tool in a way for which it was not designed. 而这一次,也许是因为我使用的工具不是针对其设计的。

I am using Paperclip for image attachments, and I'm saving these images as instances of a model called, you guessed it, Image. 我将Paperclip用于图像附件,并且将这些图像保存为名为Image的模型实例。 Images belong to users. 图像属于用户。 Users have many images. 用户有很多图像。

However, I want to specify ONE of the user's images as their default image. 但是,我想指定用户图像之一作为其默认图像。 So, my brain tells me that I need to add a field to the User table to hold the ID of the image I want to be the default. 因此,我的大脑告诉我,我需要在User表中添加一个字段以保存要成为默认图像的ID。

Images use has_attached_file. 图片使用has_attached_file。 I don't want users to have their own attached file, I just want the user model to be able to reference a specific instance of an image that has the url helper methods available to it. 我不希望用户有自己的附件,我只是希望用户模型能够引用具有url helper方法可用的图像的特定实例。

The problem comes in when I'm trying to get the URL for this image using the ID. 当我尝试使用ID获取该图像的URL时出现问题。 Either what I'm trying to do is impossible using paperclip, or I don't have my associations set up correctly. 使用回形针无法完成我想做的事情,或者我没有正确设置关联。

Basically I want to be able to access that image in a view, using an instance of a user model. 基本上,我希望能够使用用户模型的实例在视图中访问该图像。 So: 所以:

<%= image_tag @user.image.url %>

But this doesn't work. 但这是行不通的。 I get why it doesn't work, but I don't understand how to make 我知道为什么它不起作用,但我不知道如何制作

@user.image

be an instance of a magical paperclip object that has the methods attached to it to retrieve the url. 是魔术回形针对象的实例,该对象具有附加的方法来检索url。

Basically if I knew how to get a paperclip image's URL using the images ID i'd be golden. 基本上,如果我知道如何使用图像ID获取回形针图像的URL,那将是黄金。 Any clues? 有什么线索吗?

I suppose you can get the paperclip image URL from the image object? 我想您可以从图像对象获取回形针图像URL?

If so, add this to you users model: 如果是这样,请将其添加到您的用户模型中:

def image_url
  Image.find( self.image ).url
end

When you now have the ID of the default picture saved in the user model "image" column and the url of an image in the "url" column in the Image model, you should be able to do this: 现在,当您在用户模型的“图像”列中保存了默认图片的ID,并且在图像模型的“ URL”列中保存了图像的URL时,您应该可以执行以下操作:

@user.image_url

And this should return the url of your "default" image 这应该返回您的“默认”图片的网址

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM