【问题标题】:Using form_for for one-to-one relation model in rails将 form_for 用于 Rails 中的一对一关系模型
【发布时间】:2013-12-13 07:48:25
【问题描述】:

我有一个用户和个人资料的一对一模型。

下面是设备创建的User模型的代码。

class User < ActiveRecord::Base  
  has_one :profile , dependent: :destroy
end

Profile 型号的代码。

class Profile < ActiveRecord::Base   
  belongs_to :user  
end

现在我有基本的Profile 用于注册时创建的User。现在如何使用提供current_userform_for 的辅助设备来编辑用户配置文件?

【问题讨论】:

    标签: ruby-on-rails devise form-for belongs-to has-one


    【解决方案1】:

    我们做了这样的事情:

    #app/models/user.rb
    Class Model < ActiveRecord::Base
        before_create :build_profile
    end
    

    这会在数据库中填充个人资料记录,以便您稍后对其进行更新

    保存用户后,您最好使用accepts_nested_attributes_for 通过用户表单填充和保存profile 选项,如下所示:

    #config/routes.rb
    resources :users do
       resources :profiles 
    end
    
    #app/views/profiles/edit.html.erb
    <%= form_for @profile do |f| %>
         <%= f.hidden_field :user_id, current_user.id %>
         <%= f.text_field :your_profile_options %>
    <% end %>
    

    这是一个非常基本的方法,但希望能给你更多的想法。如果你想在野外看到这个,请查看http://video-conference-demo.herokuapp.com(它使用 Devise 来处理用户并且还有额外的“配置文件”模型)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2013-02-12
      • 2011-06-04
      相关资源
      最近更新 更多