要啓動此代碼屬於,我是一個相當新的到Rails是否在模型或控制器
我已經創造了一些方法,並把它們放到我的模型,但它看起來凌亂,如果代碼只是想知道屬於模型還是控制器?什麼讓我的代碼獨特(每個控制器不是一個模型)是我只有一個模型「產品」,但有3個控制器與它交互,「商家,類別,品牌」。也許有一種更簡單的方法,我完全忽略了?我真的不想將數據分成3個表格/模型之間的鏈接。
p.s.這是我第一次擺脫Rails書籍的安慰,所以請放輕鬆點!任何其他一般的建議,我的代碼將不勝感激。
產品型號
class Product < ActiveRecord::Base
validates :brand, :presence => true
def product_name
name.capitalize.html_safe
end
def product_description
description.html_safe
end
#Replace '-' with ' ' for nice names
def brand_name
brand.capitalize.gsub('-',' ')
end
def category_name
category.capitalize.gsub('-',' ')
end
def merchant_name
merchant.capitalize.gsub('-',' ')
end
#Replace ' ' with '-' for urls
def brand_url
brand.downcase.gsub(' ','-')
end
def category_url
category.downcase.gsub(' ','-')
end
def merchant_url
merchant.downcase.gsub(' ','-')
end
end
招控制器
class MerchantsController < ApplicationController
def index
@merchants = Product.find(:all, :select => 'DISTINCT merchant')
end
def show
@products = Product.find(:all, :conditions => ['merchant = ?', params[:merchant]])
@merchant = params[:merchant].capitalize.gsub('-',' ')
end
end
商家視圖(指數)
<h1>Merchant list</h1>
<%= @merchants.count%> merchants found
<% @merchants.each do |merchant| %>
<p><%= link_to merchant.merchant_name, merchant.merchant_url %></p>
<% end %>
商家視圖(顯示)
<h1>Products from merchant: <%= @merchant %></h1>
<%= @products.count%> products found
<% @products.each do |product| %>
<h3><%= product.product_name %></h3>
<p>
<img src="<%= product.image %>" align="right" alt="<%= product.product_name %>" />
<%= product.product_description %>
</p>
<p><%= product.price %></p>
<p>Brand: <%= product.brand_name %></p>
<p>Category: <%= product.category_name %></p>
<p>Sub category: <%= product.sub_category %></p>
<p>Merchant: <%= product.merchant_name %></p>
<p><a href="<%= product.link %>" target="_blank">More information</a></p>
<hr />
<% end %>
我想我需要正常化,謝謝 – Zinc 2011-02-06 18:54:27