leafshinobi25
leafshinobi25

Reputation: 67

Showing User Profile

I've been trying to get this right and after hours I'm finally just lost. I'm attempting to create a profile for a user. I separated the profile model and user model because of the attributes and the types of user's I have. The user has a has_one relationship to the profile. My problem seems to be I'm confused with not only the routes but also the controller of the profile. I simply want to be able to have a link_to to show a user's profile. But on to the code

user.rb

has_one  :profile
after_create :create_profile
def create_profile
  self.profile.create(:name => self.user_name)
end

Profile model

profile.rb
belongs_to :user, required: true, autosave: true

routes for profile

resources :profile 

profile controller

class ProfilesController < ApplicationController
  before_action :owned_profile, only: [:edit]
  before_action :get_profile
  layout "profile"
  respond_to :html, :js

  def show
    @activities = PublicActivity::Activity.where(owner:@user).order(created_at: :desc).paginate(page: params[:page], per_page: 10)
  end

  def followers
    @followers = @user.user_followers.paginate(page: params[:page])
  end

  def edit
  end

  def update
    if @profile.update(profile_params)
      flash[:notices] = ["Your profile was successfully updated"]
      render 'show'
    else
      flash[:notices] = ["Your profile could not be updated"]
      render 'edit'
    end
  end

  private

  def profile_params
    params.require(:profile).permit(:name, :cover)
  end

  def owned_profile
    unless current_user == @user
      flash[:alert] = "That profile doesn't belong to you!"
      redirect_to root_path
    end
  end

  def get_profile
    @profile = Profile.find(params[:id])
  end
end

I'm completely lost on what I need to do, should I add something to the user's controller because of the after_create method? should my resources :profile be under resources :user?

The error I get when I try to view a user profile is Couldn't find Profile with 'id'=

the link_to method I am using is <%= link_to "View Profile", profiles_show_path(@user) %>

Please let me know anything that might be of help thank you for your time and help. again I don't want to just show a user's "show" as a profile because of the different types of user's and the way I plan to model the profiles.

Upvotes: 0

Views: 863

Answers (1)

Chakreshwar Sharma
Chakreshwar Sharma

Reputation: 2610

Use the below code:

<%= link_to "View Profile", @user.profile %>

Upvotes: 0

Related Questions