`
black_star
  • 浏览: 33102 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

ruby on rails(5)--创建目录列表

阅读更多
首先创建一个控制器  ruby script/generate controller store index 会产生一个store_controller控制器及index方法。同时在view/store/index.html.erb index action是rails默认的action
     我们的目的是创建一个目录列表。首先考虑在哪里创建。在mvc结构中。v第一个被排除。那么就是m,c。m与数据库交互,c控制。因此c最合适。书上说这是为了产生抽象方法。
class StoreController < ApplicationController
  def index
  	@products = Product.find_products_for_sale
  end
end

Product 类名 find_products_for_sale方法
方法find_products_for_sale 在m中定义。在model/product.rb定义如下
	def self.find_products_for_sale
		find(:all, :order => "title")
	end

self 产生一个类方法 这样Product.find_products_for_sale就可以使用了。find取出表中字段all全部字段,也可自己选择 find(:all,:select => "id,name")这样只取id,name了和SELECT id, name FROM 一样。:order排序


然后就是在view中展示了
<% for product in @products -%> #一个product 代表一条语句
	<%= image_tag(product.image_url) %>
	<h3><%=h product.title %></h3>
	<%= product.description %>
	<span calss="price"><%= product.price%>
<% end %>

ps:c层可以调用m层方法,m层方法最好写成类方法。这样调用方便。只需在方法前加self即可。v层可以直接调用c层变量如@products
    如果出现 no route match,可重启服务器试试,我重试了,效果还是一样,后来发现controller写错了。
  • 大小: 10.4 KB
分享到:
评论
3 楼 black_star 2009-11-26  
多谢支持,小弟一定坚持下去
2 楼 Hooopo 2009-11-26  
路过,踩踩。
加油,加油!
1 楼 夜鸣猪 2009-11-26  
路过,我踩

加油,加油

相关推荐

Global site tag (gtag.js) - Google Analytics