【问题标题】:Access image from different view in a view with paperclip gem ruby on rails在轨道上使用回形针宝石红宝石的视图中从不同视图访问图像
【发布时间】:2013-09-13 04:05:07
【问题描述】:

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

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

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

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

但不工作,所以朋友,我该如何解决这个问题?谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby controller paperclip


    【解决方案1】:

    首先,在原因控制器中,将@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])
    

    【讨论】:

      【解决方案2】:

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

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

      在视图中,现在您可以使用此@profile 来获取图像。

      【讨论】:

        猜你喜欢
        • 2015-02-18
        • 1970-01-01
        • 2015-09-08
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 2022-08-15
        • 1970-01-01
        相关资源
        最近更新 更多