Profile Model with Developers in Rails

I'm trying to create a separate profile model for developer users with things like location, bio, blah, blah, blah. The problem is I can't get it to save the database.

My users are called "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 %>

      

What am I doing wrong here?

+3


source to share


3 answers


You need to initialize the profile with an object 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

      

Update:



To use this example, your association should be like

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

      

+2


source


Make sure to set the artist_id for the profile before configuring.

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

      

or



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

      

must work.

0


source


Your controller is missing a profile_params method.

private 

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

      

0


source







All Articles