views:

45

answers:

3

I'm pulling data from Harvest. Here are my two models and schema:

# schema
create_table "clients", :force => true do |t|
  t.string   "name"
  t.integer  "harvest_id"      
end

create_table "projects", :force => true do |t|
  t.string   "name"
  t.integer  "client_id"
  t.integer  "harvest_id"
end

# Client.rb
has_many :projects, :foreign_key => 'client_id' # not needed, I know

# Project.rb
belongs_to :client, :foreign_key => 'harvest_id'

I'm trying to get the Projects to find their client by matching Project.client_id to a Client.harvest_id. Here is what I'm getting instead.

> Project.first.client_id
=> 187259

Project.first.client
=> nil

Client.find(187259).projects
=> []

Is this possible? Thanks!

A: 

Since your belongs_to relationship in Project model is on harvest_id, you have to ensure the harvest_id attribute is set in the project object.

> Project.first.harvest_id
=> ??

Your problem can occur if the harvest_id is not set.

KandadaBoggu
A: 

Projects to find their client by matching Project.client_id to a Client.harvest_id

This does not seem to make sense as client and harvest are supposed to be different objects/records and you cannot match them.

It is like "Find apples where there are Orange-like seeds".

So we probably need more context.


You defined your relations the following way:

On the Project side you say "it is related to client via client_id", but on the Client you say that "it is related to Project via harvest_id"

There you have discrepancy.

So it seems you just have incorrect mappings defined.

Not sure how harvest_id is supposed to be used, so will make the assumption it is just association:

# Client.rb
has_many :projects
belongs_to :harvest

# Project.rb
belongs_to :client
belongs_to :harvest

# Harvest
has_one :client
has_one :project
Dmytrii Nagirniak
A: 

Might not seem intuitive, but the foreign_key for both relations has to be the same. Let's say you decide to use harvest_id as the foreign key. It should be set up like this:

# Client.rb
has_many :projects, :foreign_key => 'harvest_id'

# Project.rb
belongs_to :client, :foreign_key => 'harvest_id'

You would also only have the harvest_id field in the projects table, since the client has_many projects.

Karl