Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 运行不同模型的创建操作时更新用户表_Ruby_Ruby On Rails 4_Devise - Fatal编程技术网

Ruby 运行不同模型的创建操作时更新用户表

Ruby 运行不同模型的创建操作时更新用户表,ruby,ruby-on-rails-4,devise,Ruby,Ruby On Rails 4,Devise,只是想告诉你我是如何做到这一点的: 每个用户都有许多配置文件。每个概要文件都有由单个表继承(业余、专业和其他)识别的类型。我需要在某处以某种方式存储当前的\u配置文件 专业控制器 class ProfessionalsController < ApplicationController def create @professional = Professional.new(professional_params) @user = current_user @profession

只是想告诉你我是如何做到这一点的:

每个用户都有许多配置文件。每个概要文件都有由单个表继承(业余、专业和其他)识别的类型。我需要在某处以某种方式存储当前的\u配置文件

专业控制器

class ProfessionalsController < ApplicationController
def create
  @professional = Professional.new(professional_params)
  @user = current_user
  @professional.user_id = current_user.id
  @update_current_profile = User.update(@user, {:current_profile => @professional.id})
  if @professional.save
    ...
  else
    ...
  end
end

private

  def professional_params
    params.require(:professional).permit(:id, :username, :user_id)
  end

end
对于不同的事物,例如:

@update_current_profile = User.update(@user, {:current_profile => @professional.user_id})

它将数据完美地存储在User.current_配置文件中

我也在尝试没有身份证的@professional。为什么会这样

另一个问题是。这是存储用户当前_配置文件的最佳方式吗?你能给我推荐更好/更安全/更高效的解决方案吗


谢谢大家。

@professional
是一个新的未保存记录,因此还没有
id
。保存
@professional
记录后,只能更新
当前的\u配置文件

只需将行重新排序一点,就可以了:

def create
  @professional = Professional.new(professional_params)
  @user = current_user
  @professional.user_id = current_user.id
  if @professional.save
    @update_current_profile = User.update(@user, {:current_profile => @professional.id})
    # ...
  else
    # ...
  end
end

还有一个提示:在这个方法中使用了许多实例变量(带有
@
)。我对您的代码了解不够,但我建议您看看是否可以用局部变量替换其中的一些代码。经验法则:当您希望与其他方法或视图共享实例变量时,仅在控制器中使用该变量。

太好了。谢谢我以前试过这个,总是出现“缺少模板”的错误。我认为这是因为缺少用户/编辑(更新)模板。当然,这是因为在保存这些东西后没有给出行为:D:D谢谢你给我指出解决方案。这是我第一次做这样的事情。顺便问一下,你认为这种存储当前用户的方式是一件好事吗?你能换一种方式试试吗?
@update_current_profile = User.update(@user, {:current_profile => 3})
def create
  @professional = Professional.new(professional_params)
  @user = current_user
  @professional.user_id = current_user.id
  if @professional.save
    @update_current_profile = User.update(@user, {:current_profile => @professional.id})
    # ...
  else
    # ...
  end
end