drewwyatt
drewwyatt

Reputation: 6027

What is the correct way to access an instance variable in a model method from another controller?

I created some scaffolding to manage audio clips which are going to be organized by index:

rails generate scaffold Clips name:string

I uploaded all the clips to my file server, and added them to the db using the auto generated rails control panel.

Now, I need to be able to access them, so I added a url method to the model:

class Clip < ActiveRecord::Base
    def self.url
        "http://example.file_server.com/audio-clips/#{@id}.mp3"
    end
end

Now, in the controller than runs the site itself, calling this method looks like it outputs everything but the id....

class TwilioController < ApplicationController
    def index

        Twilio::TwiML::Response.new do |r|
            @response = r.play Clip.where(name: "root").url
        end

        render :xml => @response
    end
end

Outputs:

<Response>
<play>http://example.file_server.com/audio-clips/.mp3</play>
</Response>

How can I get this thing to insert the id into the URL string?

Upvotes: 0

Views: 38

Answers (1)

Nick Veys
Nick Veys

Reputation: 23939

A few things, one, you defined url as self.url, which makes it a class level method. I'm guessing you didn't want to do that.

Also, don't use id as an instance variable, use its generated accessor method:

class Clip < ActiveRecord::Base
  def url
    "http://example.file_server.com/audio-clips/#{id}.mp3"
  end
end

Also, you are calling url right after the where call, which returns a relation. You'll want to do something like:

Twilio::TwiML::Response.new do |r|
  @response = r.play Clip.where(name: "root").first.url
end

But that depends more on what you are doing. If you expect there to be several results, you'll have to handle it differently. Also beware it may return no results...

Upvotes: 1

Related Questions