问题
I have a fairly simple query to return the first record in a many-to-many relation or create one if it doesn't exist.
UserCategorization.where(category_id: 3, user_id: 5).first_or_create
My model looks like:
class UserCategorization < ActiveRecord::Base
belongs_to :user
belongs_to :category
self.primary_key = [:user_id, :category_id]
end
However it generates an invalid column name in the SQL:
SQLite3::SQLException: no such column: user_categorizations.[:user_id, :category_id]:
SELECT "user_categorizations".* FROM "user_categorizations" WHERE
"user_categorizations"."category_id" = 3 AND "user_categorizations"."user_id" = 5
ORDER BY "user_categorizations"."[:user_id, :category_id]" ASC LIMIT 1
If I remove self.primary_key = [:user_id, :category_id] from the model, it can retrieve the record correctly but cannot save because it doesn't know what to use in the WHERE clause:
SQLite3::SQLException: no such column: user_categorizations.:
UPDATE "user_categorizations" SET "score" = ?
WHERE "user_categorizations"."" IS NULL
Has anyone seen this before?
回答1:
I think one of these two suggestions will work:
First, try adding the following migration:
add_index :user_categorizations, [:user_id, :category_id]
Make sure to keep self.primary_key = [:user_id, :category_id] in your UserCategorization model.
If that doesn't work, destroy the UserCategorization table and run this migration:
def change
create_table :user_categorizations do |t|
t.references :user
t.references :category
t.timestamps
end
end
references are new to Rails 4. They add a foreign key and index to the specified columns.
Good Luck!
回答2:
So it looks like Rails 4 ActiveRecord doesn't do composite keys very well so many-to-many models create the issues above. I fixed it by using this extension to ActiveRecord: http://compositekeys.rubyforge.org/
来源:https://stackoverflow.com/questions/18905945/rails-4-generating-invalid-column-names