Rails路由和模型的问题

时间:2012-12-29 17:40:09

标签: ruby-on-rails ruby-on-rails-3

我有2个模型 - 用户模型和个人资料模型。我已按如下方式设置关系:

class User
  has_one :profile
end

class Profile
  belongs_to :user
end

我有一个包含4个动作的配置文件控制器 - 新的创建编辑和更新。用户注册或登录后,他将被重定向到“个人档案”控制器中的“新建”操作。从这里如何为该用户创建配置文件?具体来说,我应该在我的新动作和创建动作中拥有什么。现在,新操作的路径只是profile / new,它不会捕获用户参数。我试图这样做,但失败了。

配置文件控制器

def new
    @user = User.find(params[:id])
    @profile = @user.build_profile
  end

  def create
    @profile = current_user.build_profile(params[:profile])
    if @profile.save
      redirect_to current_user
    else
      render new
    end
  end

2 个答案:

答案 0 :(得分:2)

配置文件控制器中的new操作不需要从params获取用户的id。 所以你的控制器就像这样

def new
  @user = current_user
  @profile = @user.build_profile
end

def create
  @profile = current_user.build_profile(params[:profile])
  if @profile.save
    redirect_to current_user
  else
    render new
  end
end

实际上将id用户发送到new操作可能是一个安全漏洞,因为我可以发送另一个用户的id并为其他用户创建配置文件系统,不应该被允许。

答案 1 :(得分:2)

您不应在新操作中使用User.find(params[:id]

就像下面的创建操作一样,您应该Usercurrent_user

除了无法正确获取User之外还有更多问题吗?