Rails 中设计用户的配置文件模型

Profile Model with Devise Users in Rails

我正在尝试为 Devise Users 创建一个单独的配置文件模型,其中包含位置、传记等内容。问题是我无法将其保存到数据库中。

我的用户叫"artists"。

### /routes.rb ###

get 'artists/:id/new_profile' => 'artists/profiles#new', as: :profile
post 'artists/:id/new_profile' => 'artists/profiles#create'

### artists/profiles_controller.rb ###

class Artists::ProfilesController < ApplicationController

  before_action :authenticate_artist!

  def new
    @artist = current_artist
    @profile = ArtistProfile.new
  end

  def create
    @artist = current_artist
    @profile = ArtistProfile.new(profile_params)
    if @profile.save
      redirect_to current_artist
    else
      render 'new'
    end
  end
end

### /artist.rb ###

class Artist < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable
  has_one :artist_profile, dependent: :destroy

### /artist_profile.rb ###

class ArtistProfile < ActiveRecord::Base
  belongs_to :artist
  validates :artist_id, presence: true
end

### /views/artists/profiles/new.html.erb ###

<%= form_for(@profile, url: profile_path) do |f| %>
  <div class="field">
    <%= f.label :biography, "biography", class: "label" %>
    <%= f.text_area :biography, autofocus: true , class: "text-field" %>
  </div>
  <div class="field">
    <%= f.label :location, "location", class: "label" %>
    <%= f.text_field :location, class: "text-field" %>
  </div>
  ...
  ...
  ...
  <div class="actions">
    <%= f.submit "create profile", class: "submit-button" %>
  </div>
<% end %>

我做错了什么?

确保在尝试保存之前为配置文件设置 artist_id。

@profile = ArtistProfile.new(profile_params, artist_id: @artist.id)

@profile = ArtistProfile.new(profile_params)
@profile.artist_id = @artist.id

应该可以。

您需要使用 current_artist 对象初始化配置文件。

class Artists::ProfilesController < ApplicationController
  before_action :authenticate_artist!

  def new
    @artist = current_artist
    @profile = @artist.build_profile
  end

  def create
    @artist = current_artist
    @profile = @artist.build_profile(profile_params)
    if @profile.save
      redirect_to current_artist
    else
      render 'new'
    end
  end
end

更新:

要使用这个例子,你的关联应该是这样的

class Artist < ActiveRecord::Base
  has_one :profile, class_name: ArtistProfile
end

在您的控制器中,您缺少 profile_params 方法。

private 

def profile_params
        params.require(:profile).permit(:biography, :location)
end