Thi*_*ent 5 routes ruby-on-rails rails-routing ruby-on-rails-4
在我们的 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
Run Code Online (Sandbox Code Playgroud)
以下是相应的迁移:
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
Run Code Online (Sandbox Code Playgroud)
这里的技巧是,我们有一个多对多的关系,用户有许多日历,日历有许多用户,两者都是通过管理连接表实现的。
我们需要显示两者:
首先,我们考虑将 the 嵌套resources在文件中routes,例如这样:
resources :users do
resources :administrations
resources :calendars
end
Run Code Online (Sandbox Code Playgroud)
但后来我们想知道是否也可以以相反的方式嵌套它们,如下所示:
resources :calendars do
resources :administrations
resources :users
end
Run Code Online (Sandbox Code Playgroud)
这能让我们实现我们所需要的吗?这是一个好的做法(甚至是可能的做法)吗?
如果没有,我们应该如何构建我们的路线?
更新:以下路由结构怎么样:
resources :users do
resources :administrations
end
resources :calendars do
resources :administrations
end
Run Code Online (Sandbox Code Playgroud)
我们可以将一种资源嵌套到另外两种不同的资源中吗?
您可以使用Routing Concerns将一项资源嵌套到两个或多个其他资源中。例如:
concern :administratable do
resources :administrations
end
resources :users, concerns: :administratable
resources :calendars, concerns: :administratable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2599 次 |
| 最近记录: |