Forum: Ruby on Rails models that reference models that occur later in the migrati

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
22cff534e3e25802bf451fd61f0d0e5d?d=identicon&s=25 andrewdmason@gmail.com (Guest)
on 2007-02-21 05:19
(Received via mailing list)
Hello,

I have a relationship definition in my model definition, campaign.rb
that references another model, campaign_memberships.rb, that isn't
created until a later migration.

  has_many  :active_memberships,
            :class_name => "CampaignMembership",
            :foreign_key => "campaign_id",
            :conditions =>
["campaign_memberships.campaign_membership_status_id != ?",
CampaignMembershipStatus.find_by_code('resigned').id]


When I run the migration from the beginning, it bombs out here.
What's the best way to get around this problem?

Thanks,

Andrew
52cb4115a870ff1942e7e1ae96f4306f?d=identicon&s=25 Tyler MacDonald (Guest)
on 2007-02-21 05:46
(Received via mailing list)
andrewdmason@gmail.com <andrewdmason@gmail.com> wrote:
> I have a relationship definition in my model definition, campaign.rb
> that references another model, campaign_memberships.rb, that isn't
> created until a later migration.

If the problem is really the order (but I'm not convinced it is, see
below),
change the order of the migration, so that campaign_memberships happens
first. Assuming these are in the "db/migrate" directory, the way to do
this
is to name them like:

001campaign_memberships.rb
002campaign.rb

If you use the "scripts/generate migration" command to create your
migrations, the order should be sorted out for you naturally.

>
>   has_many  :active_memberships,
>             :class_name => "CampaignMembership",
>             :foreign_key => "campaign_id",
>             :conditions =>
> ["campaign_memberships.campaign_membership_status_id != ?",
> CampaignMembershipStatus.find_by_code('resigned').id]

Also, you shouldn't need to reference any actual model object here...
the
migrations should really be thought of as a lower level than that. You
could
make the "conditions' an actual SQL statement like

:conditions =>
  "campaign_memberships.campain_membership_status_id = " +
  "(SELECT id FROM campaign_membership_status WHERE code = 'resigned')"

  - Tyler
This topic is locked and can not be replied to.