
Quick scenario for the project: you’re trying to create a rails application with users that have a portfolio (for others, it’ll be profile or account page).
Assumption/Steps:
- Your rails application has a home index page and is your root page. {Route.rb => root to: “home#index”}
- You have generated devise User
- You have added extra fields to user forms. For my project I added a name and about field. My application_controller.rb:
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protect_from_forgery with: :exception
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :about])
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :about])
end
end
The Github devise page gives a detailed tutorial on how to do that.
- You have a portfolio model, controller, . . . (Yours may be profile or account). For my project, I did:
rails g scaffold portfolio head_line:string
user.rb => class User < ApplicationRecord has_one :portfolio, dependent: :destroy before_create :build_portfolio accepts_nested_attributes_for :portfolio end portfolio.rb => class Portfolio < ApplicationRecord belongs_to :user end
rails g migration add_user_id_to_portfolios user_id:integer
- Now start your rails server and create a new user. When you click the submit button, the user and portfolio page will be created and you should be redirected to your home page as the root page.
- It would be safe to delete the index function in portfolio controller as well as the index.html.erb in your portfolio view. and to routes you’d want to change resources :portfolios to resources :portfolios, except: [:index]
- Now you’re in your home page and there’s no link to redirect to the portfolio page. Let’s fix that.
home_controller.rb =>
class HomeController < ApplicationController
def index
@portfolio = Portfolio.find(current_user.portfolio[:id])
end
end
/views/home/index.html.erb =>
<p><%= link_to "My Portfolio", "/portfolios/#{@portfolio.id}" %></p>
refresh the page and try the link.
/views/portfolios/show.html.erb => <h3><%= @portfolio.user.name %>'s Portfolio</h3> <p><strong>Portfolio Link: </strong>http://localhost:3000/portfolios/<%= @portfolio.id %></p> </div> <h4>name: <%= @portfolio.user.name %></h4> <h4>About: <%= @portfolio.user.about %></h4>
. . . and that’s the end of the tutorial.
