Skip to content

Instantly share code, notes, and snippets.

@goodviber
Last active August 29, 2015 14:25
Show Gist options
  • Save goodviber/ec914b00ccef25559451 to your computer and use it in GitHub Desktop.
Save goodviber/ec914b00ccef25559451 to your computer and use it in GitHub Desktop.
Rails 4 URL setup to find model instances (eg products) by numerical id for puposes of cart addition and find by slug for purposes of SEO display. Will display in browser as app/products/my-url-goes-here, but will send params as "product_id" => 1. Completely Bonzer!
# PRODUCT MODEL
before_create do
self.slug = title.downcase.gsub(" ", "-")
end
def to_param
[id, title.parameterize].join("-")
end
#DB MIGRATION
class AddSlugToProducts < ActiveRecord::Migration
def change
add_column :products, :slug, :string
end
end
#LINEITEMS CONTROLLER
def create
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
#PRODUCT CONTROLLER
private
def set_product
@product = Product.find_by_slug(params[:id])
end
end
#PRODUCT LINKS IN A VIEW
<%= link_to image_tag(product.image_url, class: "img-responsive", style: "margin-top:10px;
width:100%;"), product %>
<%= button_to 'Add To Cart', line_items_path(product_id: product), class: "button_example center-block", style: "width:100%;
margin:10px 0;" %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment