Skip to content

Instantly share code, notes, and snippets.

@delba
Last active December 17, 2015 03:09
Show Gist options
  • Select an option

  • Save delba/5541423 to your computer and use it in GitHub Desktop.

Select an option

Save delba/5541423 to your computer and use it in GitHub Desktop.
Nesting a resource under its owner's username
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
# use default_url_options ?
def item_path(item)
super(item.user, item)
end
helper_method :item_path
end
<ul>
<% @items.each do |item| %>
<li><%= link_to item.name, item_path(item) %>
<% end %>
</ul>
class Item < ActiveRecord::Base
belongs_to :user
end
class ItemsController < ApplicationController
before_action :set_user
def index
@items = @user.items
end
def create
@item = @user.items.new(item_params)
if @item.save
# The `redirect_to @item` shortcut doesn't work
redirect_to item_path(@item)
else
render :new
end
end
private
def set_user
@user = User.find_by(username: params[:username])
end
end
MyApp::Application.routes.draw do
resources :items, path: ':username'
end
class User < ActiveRecord::Base
has_many :items
before_validation :downcase_username, if: :username_changed?
validates :username, presence: true,
uniqueness: true,
format: { with: /\A[a-z0-9_]+\z/, allow_blank: true }
def to_param
username
end
private
def downcase_username
self.username = username.dowcase
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment