recoup8063
recoup8063

Reputation: 4280

RoR Associations not working

I am trying to make a RoR project and I am currently have issues with Model Association. This is probably caused by an error or misunderstanding but in the last 2 days I have not been able to find this error or misunderstanding.

I want the associations to work like this:

User  
    => gapiToken  
    => userSession  

So that technically I could just call User.find(foo).gapiToken.

Currently I have it setup so

User  
    has_many :userSessions  
    has_one :gapiToken  

UserSession  
    belongs_to :user  

GapiToken  
    belongs_to :user

However for some reason this does not seam to be working.
For example, this piece of code:

@user = User.create(gid: foo, permissions: bar)
@gapiToken = @user.gapiToken.create(access_token: foo, token_type: bar, expires_on: bazz, refresh_token: bop)
#^ Error ^ "undefined method `create' for nil:NilClass"

Am I going about this wrong in the usage or in the setup, or both?

Complete code

Upvotes: 0

Views: 45

Answers (1)

user419017
user419017

Reputation:

First, be sure to follow conventions. Use under_scores, not camelCase:

User  
    has_many :user_sessions
    has_one :gapi_token

Second, the method @model_instance.association.create is for one-to-many associations, not one-to-one associations. It should be:

@user.create_gapi_token(...)

See here for more information about the associations API.


A note on YOUR CODE

Don't forget indexes.

A basic rule of thumb: index foreign keys, and index both keys on a join table. Example:

create_table :user_sessions do |t|
  t.belongs_to :user # will result in t.integer :user_id
end

add_index :user_sessions, :user_id

create_table :gapi_tokens, id: false do |t|
  t.belongs_to :user
end

add_index :gapi_tokens, :user_id

Example of an index on a join table (note id: false and unique: true):

create_table :users_favourites, id: false do |t|
  t.belongs_to :user
  t.belongs_to :favourite
end

add_index :users_favourites, [:user_id, :favourite_id], unique: true

Read about migrations, then read and re-read the Rails guides.

It's important you understand the conventions so you don't shoot yourself in the foot later down the road.

Upvotes: 1

Related Questions