Last active
March 19, 2016 17:09
-
-
Save durexlw/cb8fb179bc2dc1ffb26a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Party < ActiveRecord::Base | |
has_many :projects, foreign_key: :owner_id | |
has_and_belongs_to_many :projects | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Project < ActiveRecord::Base | |
belongs_to :owner, class_name: "Party" | |
has_and_belongs_to_many :contacts, class_name: "Party", foreign_key: "party_id" | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CreateJoinTableProjectParty < ActiveRecord::Migration | |
def change | |
create_join_table :projects, :parties do |t| | |
t.index [:project_id, :party_id] | |
t.index [:party_id, :project_id] | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> pr = Project.last | |
> pr.contacts | |
Party Load (0.2ms) SELECT "parties".* FROM "parties" INNER JOIN "parties_projects" ON "parties"."id" = "parties_projects"."party_id" WHERE "parties_projects"."party_id" = ? [["party_id", 496074280]] | |
=> #<ActiveRecord::Associations::CollectionProxy []> | |
> pr.contacts << Party.first | |
Party Load (0.3ms) SELECT "parties".* FROM "parties" ORDER BY "parties"."id" ASC LIMIT 1 | |
(0.2ms) begin transaction | |
SQL (1.3ms) INSERT INTO "parties_projects" ("party_id") VALUES (?) [["party_id", 397509679]] | |
(0.2ms) rollback transaction | |
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: NOT NULL constraint failed: parties_projects.project_id: INSERT INTO "parties_projects" ("party_id") VALUES (?) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Project < ActiveRecord::Base | |
belongs_to :owner, class_name: "Party" | |
has_and_belongs_to_many :parties | |
end | |
... then everything works as expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment