I would like to access “profiles” table from my Profile model which belongs_to :user “User model”.
Firstly in my show action of the users_controller I’d like to grab data from the profiles table in order to show on the users profile page.
Secondly I’d like to make it possible for users to edit these things using a form. I know this is done in the update action? while edit action makes it possible to show a form on the edit view page..
Here is my controller:
class UsersController < ApplicationController
def new
@user = User.new
@title = "Practice"
end
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
@user.build_profile.save #same as Profile.new(:user_id => @user.id)
login @user
UserMailer.join_confirmation(@user).deliver
format.js { render :js => "window.location = '#{root_path}'" }
flash[:notice] = "Welcome!"
else
format.js { render :form_errors }
end
end
end
def show
end
def update
end
def edit
end
end
1) How would I access my profiles table?
The User has_one :profile
The Profile belongs_to :user
Advice will be appreciated. Took me half of the day to figure out how to have a row corresponding to a newly created user at sign up created in the profiles table and now the next step is to be able to grab data from the model in my users_controller. i know I could just create a profiles_controller and do things there but I don’t want to attempt that right now as I’m sure there’s a way to do it via the users_controller.
Thanks in advance for advice given.
View:
<%= @profile_data.first_name %>
<h4><%= current_user.username.capitalize %></h4>
<%= gravatar_image_tag(current_user.email, :alt => @title, :class => "gravatar", :gravatar => { :size => 150 }) %>
<br />
Trying to pull first_name from profiles table through users_controller
def show
@user = User.find_by_username(params[:username])
@profile_data = @user.profile
end
route:
match ':username' => "users#show"
I expect to see the name stored in first_name column of the profiles table when i visit localhost:3000/username
it doesn’t show the users first name.
You can just do:
That will return the profile belonging to the User
Otherwise:
will return A profile object based on conditions