ruby-on-rails - 在 Rails 中设置 create_join_table 迁移选项

标签 ruby-on-rails ruby

我有一些问题。我是 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);

What I want to do is that I first of all want the table name to be users_offers instead of offers_users, for this you can specify the :table_name in the create_join_table migration. I'm not able to get the syntax of setting this option correctly. Need help here!

2nd, I noticed that this migration doesn't create the foreign keys that I would expect with the Users and Offers tables. Need your comments here also. Do I need to manually create the foreign keys myself?

最佳答案

您可以使用 table_name 选项定义您的连接表名称。

create_join_table :users, :offers, table_name: :users_offers

还有一个用于设置列选项的选项,称为 column_options,但我只让它对索引起作用,对外键不起作用。

create_join_table :users, :offers, column_options: { index: true }

这将创建所需的索引,但它会忽略 foreign_key: true。所以你需要单独创建它们。

add_foreign_key :users_offers, :users
add_foreign_key :users_offers, :offers

在您的模型中,您需要像这样添加关系:

# user.rb
has_and_belongs_to_many :offers, join_table: :users_offers

和:

# offers.rb
has_and_belongs_to_many :users, join_table: :users_offers

关于ruby-on-rails - 在 Rails 中设置 create_join_table 迁移选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338151/

相关文章:

c++ - 如何在 C/C++ 中使用 Ruby

ruby - heroku toolbelt 的问题

javascript - 如何在 Rails 应用程序中从 Javascript 写入 Heroku 的日志?

ruby-on-rails - Rails : How do I create a custom 404 error page that uses the asset pipeline?

ruby-on-rails - 警告 : already initialized constant after installing tlsmail gem?

ruby - Sequel 中的存储过程返回代码 (Ruby ORM)

ruby - 尽管#hash 和#eql 都没有结果?在哈希中查找键时评估为真?

ruby-on-rails - Rails Fixtures 没有加载 rspec

ruby-on-rails - 枚举时的不同样式(使用 each_with_index)

javascript - 在 Ruby 和 JavaScript 中复制计算的最佳方法是什么?