I am currently working on a rails project using devise, and I have ran into a bit of an issue.
I have the default devise:install running with my User model, and I have a another model called Profile. It belongs_to :user
, and the user has_one :profile
.
The issue I have, is that I require the user to have a username, so it must be done on sign up; so this is passed into the users table through devise. But I need to use the username for the users profile url, and this means crossing an attribute from the Users table, with the Profiles view.
In the user model I am using: after_create :build_profile
to build a profile for that user. This creates a profile with first_name
and last_name
etc into the profiles table.
So, using the 'friendly_id' gem I can link to attributes from the 'profiles/index'page to the users profile. The problem is I can only use things that have been passed into the profiles table, such as first_name
or last_name
I can't link to :username
as that is in the Users table, not the Profiles table.
In the profile_model.rb file, at the moment I am using:
extend FriendlyId
friendly_id :first_name
and in the profiles/index.html.erb file I am using:
<% @profiles.each do |profile| %>
<p><%= link_to profile.user.username, profile %></p>
<% end %>
This works for making URLs such as /profiles/John but John is no good as it is not unique.
Have you considered using nested routes? In your routes.rb file you can have:
resources :users do
resources :profiles
end
That way, you then use something like <%= link_to user_profile_path(@profile.user, @profile), @profile %>