如何在RoR中的不同控制器中使用模型

ash*_*hok 6 ruby-on-rails

我有一个配置文件控制器.但我想使用User模型在users表中保存一些字段.那么如何在配置文件控制器中加载用户模型?

Sal*_*lil 14

model是独立实体,您可以从任何控制器调用它.

There can be a model without a controller and vice-versa.
Run Code Online (Sandbox Code Playgroud)

对于你的问题,请看下面的例子

class ProfileController < ApplicationController

  def some_method
    @user = User.find(params[:user_id])
    if @user.update_attributes(params[:user])
       // some action
    else

       // some action
    end
  end

end
Run Code Online (Sandbox Code Playgroud)


Jer*_*iko 2

您可以在任何控制器中加载任何模型 - 只需像平常一样调用它即可。

如果您需要UserProfiles控制器加载 a,您可以只使用User.find_by_whatever(), User.new, current_profile.user- 不确定您的关联是如何设置的,但不应该有任何访问限制。

  • 您确实设置了用户模型吗?您可以从“用户”控制器中调用它吗?还是没有? (2认同)