Hopstream
Hopstream

Reputation: 6451

Which model relationship should be used here?

Table: Raw_Data Fields: id name

Table: Actual_Data Fields: id raw_data_id name

A use can either add data manually to Actual_Data (in which case it's raw_data_id is NULL) or they can select a Raw_Data to insert into Actual_Data (in which case it's raw_data_id is set).

Is the following relationships correct in this case?

For Raw_Data: -none-

For Actual_Data: has_one :raw_data

Upvotes: 0

Views: 65

Answers (2)

gustavotkg
gustavotkg

Reputation: 4399

I guess the better option is belongs_to.

Raw_Data has many or has one Actual_Data
Actual_Data belongs to Raw Data.

You just have to remember to check if raw_data is nil before doing any operations.

manually_created = ActualData.create(:name => "Something");
builded = @RawData.build_actual_data(:name => "Something else");

The first will have the column set to null, and the second exaple, will set raw_data_id to @RawData.id value.

Upvotes: 0

nkm
nkm

Reputation: 5914

You are right the relationship should be the same as you said,

class ActualDate < ActiveRecord::Base
  has_one :raw_data
end

class RawData < ActiveRecord::Base
  belong_to :actual_data
end

As per the rails convention, the foreign key should belongs to the table which has belongs_to association, so here actual_data_id should be in raw_datas table.

Edit: We don't need raw_data_id in actual_datas table.

Upvotes: 1

Related Questions