0

I currently have 2 models - Issue and Responses and i'm trying to add a method on the response model so I can do issue.responses.latest

I'm currently getting undefined method 'issue_id' for #<Class:...

How can I reference the column issue_id from the responses table in my self.latest method?

class Issue < ActiveRecord::Base
  has_many :responses
end

class Response < ActiveRecord::Base
  belongs_to :issue

  def self.latest
    select([:id, :user_id, :issue_id, :response, 'MAX(created_at)'])
       .where(:issue_id => self.issue_id) <!-- How to reference the issue_id column here?
       .group(:issue_id)
  end
end

1 Answer 1

2

You're referencing the issue_id column fine. The problem is that you're trying to provide a value of self.issue_id, but there is no issue_id class method of Response.

Also, a latest class method for Response won't be invoked by issue.responses.latest, since responses is an <ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_Collec‌​tionProxy_Table:0x007f85220bd3b8>. You could, however, define an Issue instance method of latest_response.

On a related point, since responses is an Enumerable, you can do issues.responses.max_by {|response| response.created_at}

Sign up to request clarification or add additional context in comments.

7 Comments

If i remove the self on self.issue_id I get the error undefined local variable or method 'issue_id'
Right. What are you trying to filter on? That is, what value of issue_id are you intending to specify there?
I'm ultimately trying to do issue.responses.latest in my view to get the very last response to a particular issue.
Ok, well to begin with issue.responses is going to of be of type #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Table:0x007f85220bd3b8>. If you use to_a on the end of that, you'll get an array. Defining a class method for Response is not going to help you.
You could define an Issue instance method that would let you do issue.latest_response or you could define a Response class method that would let you do Response.latest(issue.responses).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.