【发布时间】:2023-03-03 12:42:01
【问题描述】:
我有一些问题。我是 RoR 的新手
我正在尝试使用 Rails 迁移创建连接表。这方面的文档在这里... http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_join_table
当我这样做时……
rails g migration CreateJoinTableUserOffer users offers
...它会创建以下迁移
class CreateJoinTableUserOffer < ActiveRecord::Migration
def change
create_join_table:users, :offers do |t|
t.index [:user_id, :offer_id]
t.index [:offer_id, :user_id]
end
end
end
当我这样做时......
rake db:migrate
它创造...
-- Table: offers_users
-- DROP TABLE offers_users;
CREATE TABLE offers_users
(
user_id integer NOT NULL,
offer_id integer NOT NULL
)
WITH (
OIDS=FALSE
);
ALTER TABLE offers_users
OWNER TO sudeepkaushik;
-- Index: index_offers_users_on_offer_id_and_user_id
-- DROP INDEX index_offers_users_on_offer_id_and_user_id;
CREATE INDEX index_offers_users_on_offer_id_and_user_id
ON offers_users
USING btree
(offer_id, user_id);
-- Index: index_offers_users_on_user_id_and_offer_id
-- DROP INDEX index_offers_users_on_user_id_and_offer_id;
CREATE INDEX index_offers_users_on_user_id_and_offer_id
ON offers_users
USING btree
(user_id, offer_id);
我想要做的是首先我希望表名是 users_offers 而不是 offer_users,为此您可以在 create_join_table 迁移中指定 :table_name。我无法正确设置此选项的语法。在这里需要帮助!
第二,我注意到此迁移不会创建我期望的用户和优惠表的外键。这里也需要你的 cmets。我需要自己手动创建外键吗?
【问题讨论】:
-
试试这个
create_join_table(:users, :offers, table_name: "users_offers") do而不是create_join_table :users, :offers do如果你看到这里的方法代码apidock.com/rails/ActiveRecord/ConnectionAdapters/…你会看到它自动添加两列user_id和offer_id到users_offers表,它会表现作为外键,因为表名是user并且 rails 足够智能,可以将user_id视为外键,对于 offer 也是如此 -
@Athar。感谢 Athar 花时间回复我的询问。我很感激。你的建议效果很好。但是,虽然我能够创建 users_offers 表,但我无法在模型工作中获得 has_and_belongs_to_many 关系。即使我在模型中指定连接表,例如...
-
has_and_belongs_to_many:offers,join_table:users_offers
-
您能否将您为
has_and_belongs_to_many关联添加的行添加到您的问题或什至作为评论。它应该是这样的has_and_belongs_to_many :offers, join_table: "users_offers" -
@athar 我意识到我为模型关联所做的更改没有在 Rails 控制台中生效。一旦我重新启动 rails 控制台,我的更改就会生效并且一切正常。感谢您检查并回复。感谢您的帮助!
标签: ruby-on-rails ruby