从视图中的不同视图访问图像与回形针gemruby在铁轨上

我是Ruby on Rails的新手并且正在学习它。 我想在另一个视图中访问带有paperclip gem存储的图像的表,例如在我的应用程序中,我有原因控制器,我可以通过以下代码访问视图中存储在表中的图像:

=image_tag @cause.images.first.image.url(:thumb), 

但我也可以访问,从配置文件控制器存储在表中的图像。 那么,如何在视图中访问视图配置文件的对象? 我在原因控制器中尝试:

 -> @profile = Profile.all -> =image_tag @profile.images.first.image.url(:thumb), 

但是没有工作,所以朋友们,我该如何解决这个问题呢? 谢谢。

首先,在cause控制器中,复数@profile因为Profile.all将返回所有配置文件的数组。 @profile = Profile.all更改为@profiles = Profile.all

因为@profiles是一个数组,所以需要遍历视图中的每个数组项原因:

 <% @profiles.each do |profile| %> <%= image_tag profile.images.first.image.url(:thumb) %> <% end %> 

如果您只打算返回单个配置文件图像,则需要指定控制器中的配置文件。 即

 @profile = Profile.first 

或者如果原因模型属于配置文件模型:

 @profile = Profile.find(params[:profile_id]) 

您正在将Profile.all发送到@profile,这意味着@profile将成为一个配置文件对象数组。 您的方法图像将在Profile类的一个对象上工作,而不是多个。 您需要选择正确的配置文件并将其分配给@profile。 对于EX:

 @profile = Profile.first # just taking the first profile, you can select any. 

在视图中,现在您可以使用此@配置文件来获取图像。