要启动此代码属于,我是一个相当新的到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