How to correctly scope controller method to account?

I am trying to make sure this method only allows editing of data that is appropriate for the current account. I am running Rails 3.12, using acts_as_tenant for managing accounts, and devise for user authentication.

When I try to access /dataload_mailchimp/edit I get the following error:

NoMethodError (undefined method `api_key' for #<ActiveRecord::Relation:0x00000006d02590>):
2013-09-27T17:12:23.947590+00:00 app[web.1]:   app/controllers/dataload_mailchimps_controller.rb:32:in `edit'

As I understand the error an api_key is not found. However, I am logged in as a user for account_id = 3 and there is a valid api_key for that account_id in the dataload_mailchimps table.

I am trying to better understand how I scope this method correctly so the correct record from dataload_mailchimps is returned?

Thanks for any help or advice.

my controller:

class DataloadMailchimpsController < ApplicationController
  before_filter :authenticate_user!
  def edit
    @dataload = DataloadMailchimp.where( account_id: current_user.account )
    unless @dataload
      redirect_to new_dataload_mailchimp_path
      gibbon =
      @lists = []
      gibbon.lists['data'].each do |list|
        @lists << MailchimpList.find_or_create_by_list_id(:list_id => list['id'], :name => list['name'])

from the dataload_mailchimps table:

id          api_key       account_id
4	    6a3	          3

It sounds like your query is wrong. What happens if you run the following in the console:
DataloadMailchimp.where(account_id: current_user.account).to_a

Obviously, you’ll need to set current_user. Actually, you could probably just hardcode current_user.account_id to 1, as that part doesn’t seem to be the problem.

I suspect that you will end up with a SQL error.

Thanks for the suggestion. Yes, if I hard code current_user.account to 3 then the where statement returns the full record from the dataload_mailchimps table with the correct api_key that I included at the bottom of my original post. Should I be using current_user.account OR current_user.account_id?


puts current_user.account_id

and got 3 in the log which is the correct value. When I added that to my where statement I still got the same error.

So this is what got this to work:

@dataload = DataloadMailchimp.find_by_account_id(current_user.account_id)