下载了N久的<Agile web development with rails>英文版,今天开始看,记录下一些看的过程值的记录的东西...俺记忆力一般
1.几个命令:
A.创建一个应用 rails 应用名称,如rails demo
B.启动服务器,在应用目录下:ruby script/server
C.创建controller: ruby script/generate controller hello
2.几个函数:
在rhtml页面模板中使用的函数:
h()函数:告诉ROR对字符串不进行任何处理,显示特殊字符,如h(killme6115@sina.com)
link_to()函数: 处理超链接,当然,可以写成<a href="'>,但不利于应用的修改和移植,最好采用link_to()函数
如:link_to "hello!!",:action=>"hello" 其中hello就是action的名称
3.在ROR中,controller顾名思义就是控制器,类似servlet作为转发器,view下的.rhtml文件作为显示模版,module为Active Record
停了蛮久,继续写..
1.常用命令:
linux环境下:
创建数据库 mysqladmin -u root create depot_development
使用数据库 mysql -u root depot_develope
创建model ruby script/generate model Product
执行创建model的数据库脚本 rake db:migrate
生成脚本 ruby script/generate migration add_price
生成scaffold : ruby script/genearte scaffold model名 controller名
2.如何通过model创建表?
class CreateProducts < ActiveRecord::Migrationdef self.up create_table :products do |t| t.column :title, :string t.column :description, :text t.column :image_url, :string endenddef self.down drop_table :products endend
附加:增加或者删除某字段:
add_column :products, :price, :integer, :default => 0
remove_column :products, :price
上面的例子中建立的表名为model的复数形式,如products
3.如何实行验证?
(1)validates_presence_of 判断是否为空
(2)validates_numericality_of :price, :only_integer => true 判断是否为数字且仅为整数
(3)自定义validate函数:
protecteddef validateerrors.add(:price, "should be positive" ) if price.nil? || price <= 0end
(4)判断是否重复:
validates_uniqueness_of
(5)判断格式,比如url格式:
validates_format_of :image_url, :with => %r{/.(gif|jpg|png)$}i, :message => "must be a URL for a GIF, JPG, or PNG image"
4.链接CSS文件:
<%= stylesheet_link_tag 'scaffold' , 'depot' %>
或者默认:
<%= stylesheet_link_tag 'scaffold' %>
1.创建session,默认是保存在服务器上的文件系统,可以放在数据库中
(1)rake db:sessions:create 创建sessions的脚本
(2)修改config下面的enviroment.rb:
# Use the database for sessions instead of the file system# (create the session table with 'rake create_sessions_table')config.action_controller.session_store = :active_record_store
(3)创建session保存的对象,比如购物车cart:
class Cart attr_reader :items def initialize @items = [] end def add_product(product) @items << product endend
(4)在controller中得到session:
privatedef find_cart session[:cart] ||= Cart.newend
(5)清空session:
session[:cart]=nil或者
rake db:sessions:clear
2.错误处理:
创建错误消息提示flash(够奇怪的名字),相当于一个hash,里面存储了错误消息,比如:
flash[:notice] = "Invalid product"
在页面上调用:
<% if flash[:notice] -%><div id="notice" ><%= flash[:notice] %></div><% end -%>
需要注意的是rescue关键字,相当于java中的catch的意思
3.重定向:redirect_to
比如redirect_to :action => :index转移到index.rhtml
4.支持AJAX特性...只能说非常非常酷!!!区区几行代码就可以做出神奇的效果,你不得不感叹ROR的强大
需要注意的几个标签:
(1)
<%= form_remote_tag :url => { :action => :add_to_cart, :id => product } %><%= submit_tag "Add to Cart" %><%= end_form_tag %>
(2)
<%= javascript_include_tag :defaults %>
(3)rjs模板:
page[:cart].replace_html :partial => 'cart' , :object => @cart
表示ID为cart的div层的innerHTML将被_cart.rjs模板取代
(4)request.xhr? 判断浏览器是否支持javascript
1.SHA1加密:
首先,要装载模块:require "digest/sha1"
一段示范加密函数:
def self.encrypted_password(password) Digest::SHA1.hexdigest(password)end
2.我们在用户注册时要求用户重复输入两次密码来确认正确性,验证函数可以用:
在model:
attr_accessor :password_confirmationvalidates_confirmation_of :password
在页面:
<p><label for="user_password_confirmation" >重复密码:</label><%= form.password_field :password_confirmation, :size => 40 %></p>
3.过去我们一直让rails帮我们自动产生scaffold,如果我们要自己定义该如何?
ruby script/generate controller Login add_user login logout delete_user list_users
此命令将产生login controller以及add_user.rhtml等页面和action函数
4.model对象可以通过调用count函数来统计数目,比如Order.count将返回orders表的记录数
5.比较有趣的,和java中servlet的filter相似的概念,通过过滤器来控制访问权限
比如,我们想判断某个用户是否具有访问某个URL的权限,我们可以写一个函数:
def authorize unless User.find_by_id(session[:user_id]) flash[:notice] = "Please log in" redirect_to(:controller => "login" , :action => "login" ) endend
此段代码的意义很明显,判断用户是否登陆,没登陆就跳转到登陆页面,然后在需要控制访问的controller加入:
before_filter:authorize如此一来,当访问此controller所拥有的页面之前将进行过滤判断
6.rails中的ORM,比起hibernate,简单多了,真正的描述性语言,比如:
class Order < ActiveRecord::Base has_many :line_itemsend
class LineItem < ActiveRecord::Base belongs_to :orderend
两个关键字,belong_to和has_many定义了Order与LineItem之间的双向一对多关系,需要配置吗?需要注释吗?都不需要,rails已经帮你搞定一切...不过,你必须在建表的时候定义关联外键,而hibernate则不要求如此.
ActiveRecord的功能相比于hibernate来说还显得弱小,但符合rails的设计原则
1.如何把数据库中的text类型字段原样显示在页面上?(包括换行,表格,图片等)
首先安装:gem install RedCloth
然后在页面调用,比如artical的content为text类型:
<%= textilize(@artical.content) %>
2.分页,rails处理分页很简单
简单的:
@user_pages,@pages=paginate(:user,:order=>'name')
在页面上调用:<%= pagination_link(@user_pages)%> 实现了自动分页和显示功能
下面是一个自定义的分页函数,你可以放在application_controller里面:
def paginate_collection(collection, options = {}) default_options = {:per_page => 10, :page => 1} options = default_options.merge options pages = Paginator.new self, collection.size, options[:per_page], options[:page] first = pages.current.offset last = [first + options[:per_page], collection.size].min slice = collection[first...last] return [pages, slice] end 根据你传入的查询结果的集合来分页,特别适合复杂的多表查询
|