Rails: 一对多参数
Rails: one-to-many params
我正在为我的运动队制作一个网站,球员们可以在上面发表博文。
class Player < ApplicationRecord
has_many :blogs, dependent: :destroy
end
class Blog < ApplicationRecord
belongs_to :player
end
我的问题是:
使用以下两个参数设置 route/controller 动作有什么区别?他们都给我完全一样的东西。
1)
路线:
get "players/:player_id/posts" => "blogs#show", as: "player_posts"
控制器动作:
class BlogsController < ApplicationController
def show
@player = Player.find(params[:player_id])
@blogs = @player.blogs
end
end
2)
路线:
get "players/:id/posts" => "blogs#show", as: "player_posts"
控制器动作:
class BlogsController < ApplicationController
def show
@player = Player.find(params[:id])
@blogs = @player.blogs
end
end
What is the difference between setting up the route/controller action
with the following two params?
这两个命名路由之间没有区别,除了您使用的是不同键(:player_id
& :id
)。我建议第一条路线,因为您在 博客控制器 [ 中获取 players 实例 =25=].
get "players/:player_id/posts" => "blogs#show", as: "player_posts"
#controller action:
class BlogsController < ApplicationController
def show
@player = Player.find(params[:player_id]) #players instance
@blogs = @player.blogs
end
end
我正在为我的运动队制作一个网站,球员们可以在上面发表博文。
class Player < ApplicationRecord
has_many :blogs, dependent: :destroy
end
class Blog < ApplicationRecord
belongs_to :player
end
我的问题是:
使用以下两个参数设置 route/controller 动作有什么区别?他们都给我完全一样的东西。
1)
路线:
get "players/:player_id/posts" => "blogs#show", as: "player_posts"
控制器动作:
class BlogsController < ApplicationController
def show
@player = Player.find(params[:player_id])
@blogs = @player.blogs
end
end
2)
路线:
get "players/:id/posts" => "blogs#show", as: "player_posts"
控制器动作:
class BlogsController < ApplicationController
def show
@player = Player.find(params[:id])
@blogs = @player.blogs
end
end
What is the difference between setting up the route/controller action with the following two params?
这两个命名路由之间没有区别,除了您使用的是不同键(:player_id
& :id
)。我建议第一条路线,因为您在 博客控制器 [ 中获取 players 实例 =25=].
get "players/:player_id/posts" => "blogs#show", as: "player_posts"
#controller action:
class BlogsController < ApplicationController
def show
@player = Player.find(params[:player_id]) #players instance
@blogs = @player.blogs
end
end