Re: Rails HABTM records

Sachin Joshi
Wed, 06 Apr 2011 15:36:57 -0000

Hi Colin,
Thanks for the pointers, in the mean time i got a work around on the
lines you mentioned.
Since it is HABTM relationship it is fetching array of accounts.
e.g.

def index
    @user = User.find(current_user)
    @account = current_user.account
    @account.each do |a|
      @ac_id = a.id
    end
end

And i am able to use the @ac_id, but i am sure this not the clever way
to do this.
In the current specs i have 1 admin_user for 1 one account and this
account can have multiple users.

but this HABTM provision is made for future in which any of the sub
user of an existing account should be able to extend it to a owner
account.
I shall post any update..

Thanks,
Sachin

On Apr 6, 2:56 pm, Colin Law
<clan...-gM/Ye1E23mwN+BqQ9rBEUg@public.gmane.org>
wrote:
> On 6 April 2011 04:56, Sachin Joshi
<sachin.jo...-Pif7/TdT6AJWk0Htik3J/w@public.gmane.org> wrote:
>
> > Hello Experts,
> > I have a HABTM association between User and Account model through a
> > table users_accounts
>
> I am surprised it works, I would have expected Rails to look for table
> accounts_users, unless you are specifying has_many through, rather
> than HABTM.
>
> > the association seems to be working fine, e.g.
> > when i do
>
> > @user.account
>
> That should be @user.accounts.  If @user.account works then you have
> not specified the relationships correctly.
>
> > it fetches the associated record which is just one record as of now.
> > @user.account
> > => [#<Account id: 1, acc_name: "test account",
created_at: "2011-03-16
> > 10:39:03", updated_at: "2011-04-03 01:58:03">]
>
> Notice the square brackets.  This is an array of accounts, containing
> one element.
>
>
>
> > When i use @user.account.acc_name in the view, it throws the following
> > error.
>
> > undefined method `acc_name'' for #<Class:0x317e6b0>
>
> That is because @user.account is an array.  You need something like
> @user.account[0].acc_name, or @user.account.first.acc_name.
>
> If you still can''t work it out post the class definitions with the
> association specifications (copy and paste from your code so as to
> avoid confusing typos).
>
> Colin