Huub Mons
Huub Mons

Reputation: 149

passing a paperclip image from the controller to a view in rails

I have a model that has an image attached to it that I want to be passed through a controller into a view. This is the way I have tried myself but it does not work:

Model:

class CustomForm < ActiveRecord:Base
    has_attached_file :background_image,
      :storage => :s3,
      :bucket => "asdf",
      ...

    belongs_to  :project

Controller:

class FormsController < ApplicationController
    before_filter :get_project

    def show
        @form = @project.forms.find(params[:id])
        @bg_image = @form.background_image.url
    end

    def get_project
        @project = current_account.projects.find(params[:project_id])
    end

View:

<html>
    <head>
    </head>

    <body>
        <%= image_tag @bg_image %>
    </body>
</html>

This creates a "can't convert nil into String" error and points to the "<%= image_tag @bg_image %>" line, and I assume @bg_image is nil. So what am I doing wrong here?

Upvotes: 0

Views: 490

Answers (1)

Carson Cole
Carson Cole

Reputation: 4461

Uou might need to eval the image_tag line:

<%= eval("image_tag #{@bg_image}")

Since you aren't saving anything by having @bg_image set in the controller, you can just as easily do. :

<%= image_tag @form.background_image.url %>

Which will probably render a nano-second faster and it looks a lot cleaner.

Upvotes: 1

Related Questions