在 has_one 关联上显示控制器的方法
show method for controller on a has_one association
我有两个模型
thing.rb
has_one :subthing
subthing.rb
belongs_to :thing
并且正在使用
进行路由
resources :thing do
resource :subthing
end
resources :subthing
但是,我在控制器上的显示方法
def show
@subthing = Subthing.find(params[:id])
end
当我访问
http://example.org/things/1/subthing
给我一个错误
找不到没有 ID 的 Subthing
我觉得这应该由框架来处理......也就是说,应该确定相关的 Subthing 是属于 Thing 的那个。
我是不是遗漏了什么,或者我不能在这里对 Subthings 单独使用相同的控制器方法,或者当它们是事物的一部分时对 Subthings 使用相同的控制器方法。
或者我是否需要明确告知每个潜在关联的控制器。即
def show
if params[:thing_id].present?
@subthing = @thing.find(params[:thing_id]).subthing
else
@subthing = Subthing.find(params[:id])
end
end
如果您打算对嵌套资源和顶级资源使用相同的 SubthingsController
,那么是的,您需要按照建议进行操作:
def show
if params[:thing_id].present?
@subthing = @thing.find(params[:thing_id]).subthing
else
@subthing = Subthing.find(params[:id])
end
end
但是你的控制器很快就会变得复杂,不值得。您最好重新定义路线或使用两个单独的控制器。
我有两个模型
thing.rb
has_one :subthing
subthing.rb
belongs_to :thing
并且正在使用
进行路由resources :thing do
resource :subthing
end
resources :subthing
但是,我在控制器上的显示方法
def show
@subthing = Subthing.find(params[:id])
end
当我访问
http://example.org/things/1/subthing
给我一个错误
找不到没有 ID 的 Subthing
我觉得这应该由框架来处理......也就是说,应该确定相关的 Subthing 是属于 Thing 的那个。
我是不是遗漏了什么,或者我不能在这里对 Subthings 单独使用相同的控制器方法,或者当它们是事物的一部分时对 Subthings 使用相同的控制器方法。
或者我是否需要明确告知每个潜在关联的控制器。即
def show
if params[:thing_id].present?
@subthing = @thing.find(params[:thing_id]).subthing
else
@subthing = Subthing.find(params[:id])
end
end
如果您打算对嵌套资源和顶级资源使用相同的 SubthingsController
,那么是的,您需要按照建议进行操作:
def show
if params[:thing_id].present?
@subthing = @thing.find(params[:thing_id]).subthing
else
@subthing = Subthing.find(params[:id])
end
end
但是你的控制器很快就会变得复杂,不值得。您最好重新定义路线或使用两个单独的控制器。