Reputation: 345
I'm trying to create a separate Profile model for Devise Users with things such as location, biography, blah, blah, blah. The problem is that I can't get it to save to 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?
Upvotes: 3
Views: 1143
Reputation: 1381
You need to initialise the profile using the current_artist
object.
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
Upvotes: 2
Reputation: 96
In your controller you are missing the profile_params method.
private
def profile_params
params.require(:profile).permit(:biography, :location)
end
Upvotes: 0
Reputation: 13057
Make sure you set the artist_id for the profile before attempting to save.
@profile = ArtistProfile.new(profile_params, artist_id: @artist.id)
or
@profile = ArtistProfile.new(profile_params)
@profile.artist_id = @artist.id
should work.
Upvotes: 0