在rails中为用户创建一个配置文件

时间:2015-01-10 15:29:09

标签: ruby-on-rails ruby-on-rails-4 devise associations

我正在尝试创建一个具有技能,教育,经验,语言的用户个人资料......所以对此我有这种关系

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  after_create :create_profile

  private 

  def create_profile
    Profile.create(user: self)
  end   
end



 class Profile < ActiveRecord::Base

        belongs_to :user

        has_many :profile_languages, dependent: :destroy
        accepts_nested_attributes_for :profile_languages , :reject_if => lambda { |a| a[:language_name].blank? }, :allow_destroy => true
        has_many :profile_skills, dependent: :destroy
        accepts_nested_attributes_for :profile_skills , :reject_if => lambda { |a| a[:skill_name].blank? }, :allow_destroy => true

    end

但问题是在注册后转到编辑配置文件,语言和技能将无法保存

这是我的个人资料控制器

def show
    @profile = Profile.find(params[:id])
  end

  def edit
    @user = current_user
    @profile = @user.profile  
  end

  def update
    @user = current_user
    @profile = @user.profile


    if @profile.update_attributes(profile_params)
      redirect_to profile_path
    else
      flash[:notice] = @profile.errors.full_messages
      redirect_to edit_profile_path
    end
  end

private

def profile_params
      params.require(:profile).permit(:user_id, :summary, :profile_title, :useravatar, :profile_skills_attributes: [:id, :skill_name,:_destroy], profile_languages_attributes: [:id, :language, :proficiency, :_destroy] )
    end

我正在考虑在配置文件控制器中添加一个类似

的新类
  def new
    @profile = current_user.profile.build
    @profile.profile_languages.build
    @profile.profile_skills.build
  end

但我不认为这是一个很好的解决方案,因为我已经在注册后创建了个人资料,所以我想知道什么是更好的解决方案

更新

 <%= form_for @profile do |f| %>
..................
      <%= render 'profile_language_fields', f: f %>
      <%= link_to_add_fields "Add languages", f, :profile_languages %>
<%= end  %>

这是profile_language partial

<%= f.fields_for :profile_languages do |pl| %>
        <div class="plform-group">
            <div class="form-planguage-half">
              <%= pl.text_field :language, class: 'form-control form-two-half'  %>
            </div>
            <div class="form-planguage-half-last">
              <%= pl.select(:proficiency, [
                      ["Débutant", 1], 
                      ["Intermédiaire", 2], 
                      ["Courant", 3], 
                      ["Bilingue", 4], 
                      ["Natif", 5]], 
                      {}, {class: "form-control form-two-half"}) %>
            </div>
    <%= pl.hidden_field :_destroy %>
    <%= link_to "remove", '#', class: "remove_fields" %>
        </div>
<% end %> 

0 个答案:

没有答案