嵌套表单不会显示has_one关系Simple_Form(Rails 4)

时间:2017-08-23 04:22:01

标签: ruby-on-rails ruby activerecord

我将用户模型设置为在创建之前构建user_profile。加载用户对象时,user_profile本身将显示在控制台中。 @user = User.find(1) - > @ user.user_profile - > UserProfile加载。这种关系正常。问题是我无法使用edit user_profile操作更改用户配置文件。即使user_profile的属性存在,编辑页面也是空的。如何在编辑视图中加载表单,以便用户在登录其帐户后能够更改他/她的个人资料?附注:用户在注册期间不会编辑其正常配置文件。

user.rb

class User < ApplicationRecord
  # Include default devise modules.
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable
  include DeviseTokenAuth::Concerns::User
  before_create :build_user_profile
  extend FriendlyId

  after_validation :geocode

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  friendly_id :username, use: :slugged

  has_one :user_profile
  accepts_nested_attributes_for :user_profile

  protected
  def confirmation_required?
    false
  end
end

user_profile.rb

class UserProfile < ApplicationRecord
  mount_uploader :avatar, UserAvatarUploader
  belongs_to :user, :dependent => :destroy

  validates_integrity_of  :avatar
  validates_processing_of :avatar

end

_form.html.erb

<%= simple_form_for(@user_profile, :html => {:multipart => true}) do |f| %>
    <%= f.error_notification %>
    <div class="form-group">
      <% f.simple_fields_for :user_profile do |user_profile| %>
          <div class="col-md-4">
        <% if current_user.user_profile.avatar.url.present? %>
            <%= image_tag(current_user.user_profile.avatar.url) %>
            <%= user_profile.label :remove_avatar do %>
                <%= user_profile.input :remove_avatar, as: :boolean, checked_value: true, unchecked_value: false %>
            <% end %>
            <%= user_profile.input :avatar, as: :file, class: 'form-control' %>
            <%= user_profile.input :birthday, label: false, id: 'datepicker', class: 'form-control' %>

        <% end %>
            <div class="form-group">
              <div class="col-md-4">
                <%= f.button :submit %>
              </div>
            </div>
        <% end %>
<% end %>

schema.rb

 create_table "user_profiles", force: :cascade do |t|
    t.date "birthday"
    t.bigint "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "avatar"
    t.index ["user_id"], name: "index_user_profiles_on_user_id"
  end

user_profiles_controller.rb

class UserProfilesController < ApplicationController
  #before_action :set_user_profile, only: [:show, :edit, :update]
  before_action :authenticate_user!
  before_action :load_profile, only: [:edit, :update]

  def show

  end

  # GET /user_profiles/1/edit
  def edit
  end

  # PATCH/PUT /user_profiles/1
  # PATCH/PUT /user_profiles/1.json
  def update
    respond_to do |format|
      if @user_profile.update(user_profile_params)
        format.html {redirect_to @user_profile, notice: 'User profile was successfully updated.'}
        format.json {render :show, status: :ok, location: @user_profile}
      else
        format.html {render :edit}
        format.json {render json: @user_profile.errors, status: :unprocessable_entity}
      end
    end
  end

  private

  def load_profile
    @user_profile = current_user.user_profile
  end


  # Never trust parameters from the scary internet, only allow the white list through.
  def user_profile_params
    params.require(:user).permit(user_profile: [:birthday, :avatar, :user_id])
  end
end

Rails控制台

@user = User.find(5)
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 5], ["LIMIT", 1]]
#<User id: 5, email: "colejohn@hotmail.com", username: "johnny", first_name: "John", last_name: "Woo">
>> @user.user_profile
  UserProfile Load (2.0ms)  SELECT  "user_profiles".* FROM "user_profiles" WHERE "user_profiles"."user_id" = $1 LIMIT $2  [["user_id", 5], ["LIMIT", 1]]
#<UserProfile id: 2, birthday: nil, user_id: 5, created_at: "2017-08-17 20:47:12", updated_at: "2017-08-17 20:47:12", avatar: nil>

2 个答案:

答案 0 :(得分:0)

  

编辑页面为空,即使属性为   user_profile存在。

这一行

<% f.simple_fields_for :user_profile do |user_profile| %>

应该是

<%= f.simple_fields_for :user_profile do |user_profile| %>

您缺少=,这就是表单空白的原因。

答案 1 :(得分:0)

如果在simple_form

中声明终止&lt;%end%&gt; ,则错位
<% if current_user.user_profile.avatar.url.present? %>
            <%= image_tag(current_user.user_profile.avatar.url) %>
            <%= user_profile.label :remove_avatar do %>
                <%= user_profile.input :remove_avatar, as: :boolean, checked_value: true, unchecked_value: false %>
            <% end %>
         <% end %>