【问题标题】:How to connect Profile Controller with User Controller?如何连接配置文件控制器和用户控制器?
【发布时间】:2012-12-30 00:14:11
【问题描述】:

我通过 Devise 拥有 USER 并通过脚手架创建了配置文件,现在一切正常,但我无法将用户与配置文件“连接”。

这是我到目前为止所做的 -

用户.rb

has_one :profile

profile.rb

belongs_to :user

我也通过配置文件表中的迁移创建了 user_id 列。

现在,当我登录并填写表格 /profiles/new 时,它会创建配置文件,但由于 user_id 字段为 NULL,因此无法链接到用户。此外,用户可以创建多个配置文件,而我认为他只能创建一个,因为我已经提出:has_one 关系?

任何帮助?

编辑 - 在profiles_controller 文件中,我也尝试更改

@user_profile = UserProfile.new(params[:user_profile])

@user_profile = current_user.userprofile.new(params[:user_profile])

但它给出了未定义的方法'UserProfile'

【问题讨论】:

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


    【解决方案1】:
    @user_profile = current_user.userprofile.new(params[:user_profile])
    

    应该是

    @user_profile = current_user.build_user_profile(params[:user_profile])
    

    【讨论】:

    • 我觉得应该是@user_profile = current_user.build_profile(params[:user_profile])(见guides.rubyonrails.org/…
    • 我仍然遇到同样的错误 - 未定义的方法 `build_profile'
    • 啊,明白了,代码很好,@user_profile = current_user.build_user_profile(params[:user_profile]),你能告诉我 CREATE 出了什么问题,因为我以前用过它,它工作正常。
    • 如果您自己创建用户配置文件,它将没有user_id。在current_user 上建立关联会正确设置user_id。就是这么简单。
    • 您的个人资料模型似乎被称为 UserProfile 所以我已经回滚了 Baldrick 的答案编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2012-10-18
    相关资源
    最近更新 更多