在我们的 Rails 4 应用程序中,有四种模型:
class User < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :calendars, through: :administrations
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Calendar < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :users, through: :administrations
end
class Post < ActiveRecord::Base
belongs_to :calendar
end
以下是相应的迁移:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.integer :total_calendar_count
t.integer :owned_calendar_count
t.timestamps null: false
end
end
end
class CreateAdministrations < ActiveRecord::Migration
def change
create_table :administrations do |t|
t.references :user, index: true, foreign_key: true
t.references :calendar, index: true, foreign_key: true
t.string :role
t.timestamps null: false
end
end
end
class CreateCalendars < ActiveRecord::Migration
def change
create_table :calendars do |t|
t.string :name
t.timestamps null: false
end
end
end
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.references :calendar, index: true, foreign_key: true
t.date :date
t.time :time
t.string :focus
t.string :format
t.string :blog_title
t.text :long_copy
t.text :short_copy
t.string :link
t.string :hashtag
t.string :media
t.float :promotion
t.string :target
t.integer :approval
t.text :comment
t.timestamps null: false
end
end
end
这里的技巧是我们有一个多对多的关系,用户有很多日历,日历有很多用户,两者都通过管理连接表。
我们需要同时显示:
首先,我们想到了嵌套
resources
在 routes
文件,例如这样:resources :users do
resources :administrations
resources :calendars
end
但后来我们想知道我们是否也可以反过来嵌套它们,如下所示:
resources :calendars do
resources :administrations
resources :users
end
这能让我们实现我们所需要的吗?这是一个好的做法(或者甚至是可能的)?
如果没有,我们应该如何构建我们的路线?
更新 :下面的路由结构怎么样:
resources :users do
resources :administrations
end
resources :calendars do
resources :administrations
end
我们可以将一种资源嵌套到两种不同的其他资源中吗?
最佳答案
您可以使用 Routing Concerns 将一个资源嵌套到两个或多个其他资源中.例如:
concern :administratable do
resources :administrations
end
resources :users, concerns: :administratable
resources :calendars, concerns: :administratable
关于ruby-on-rails - rails 4 : how to implement routes for a many-to-many relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31258275/