【发布时间】:2011-02-06 18:36:48
【问题描述】:
首先,我是 Rails 的新手
我创建了一些方法并将它们放入我的模型中,但它看起来很乱,只是想知道代码是属于模型还是控制器?是什么让我的代码独一无二(每个控制器都不是一个模型)是我只有一个模型“产品”,但有 3 个与之交互的控制器,“商家、类别、品牌”。也许我完全忽略了一种更简单的方法?我真的不想将数据拆分为 3 个表/模型之间的链接。
附言这是我第一次从舒适的 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 %>
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3