0
点赞
收藏
分享

微信扫一扫

ror学习小结5

伢赞 2022-12-08 阅读 89

1 一对一关系,假设student和mealcard为两个一对一关系的类 

class Student < ActiveRecord::Base

has_one(:meal_card, :class_name => "MealCard", :foreign_key => "student_id")

end


class MealCard < ActiveRecord::Base

belongs_to(:student, :class_name => "Student", :foreign_key => "student_id")

end




2 一对多关系

比如产品和分类一对多关系

分类:

class Type < ActiveRecord::Base

has_many(:products,:class_name=>"Product", :foreign_key=>"type_id")

end


class Product < ActiveRecord::Base

belongs_to(:type,:class_name=>"Type", :foreign_key=>"type_id")

end

调用:

<% @types.each do |type| %>

<% type.products.each do|p| %>

<tr>

<%if(temp_id != type.id)

temp_id = type.id %>

<td rowspan="<%= type.products.size %>"><%= type.id %></td>

<td rowspan="<%= type.products.size %>"><%= type.name %></td>

<% end %>


<td><%= p.name %></td>

<td><%= p.model %></td>


3 多对多



比如角色和function的多对多关系



class Role < ActiveRecord::Base

has_and_belongs_to_many(:functions,:class_name=>"Function",:join_table=>"functions_roles")

end

class Function < ActiveRecord::Base

has_and_belongs_to_many :roles

end


4 无限分级的菜单

class Menu < ActiveRecord::Base

belongs_to(:parent,

:class_name=>"Menu",

:foreign_key=>"parent_id")

has_many(:childs,

:class_name=>"Menu",

:foreign_key=>"parent_id")

end


5 使用activerecord中的事务处理

比如

类名.transcation do

.....

end



6 validate自定义

validate_on_create:在数据库创建记录时,对保存的数据验证

validate_on_update:在修改记录时,对数据进行验证

class User < ActiveRecord::Base

def validate

if name.blank?

errors.add(:name, "姓名不能为空!")

end


if year < 1910 or year > 2011

errors.add(:year, "出生年份必需在1910年到2011年之间")

end


if sex.blank?

errors.add(:sex, "性别不能为空!")

end


if not phone.match(/((0\d{3}|\d{2})-(\d{7}|\d{8}))|(1\d{10})/)

errors.add(:phone, "电话号码格式错误!")

end

end

end

<% if @user.errors.any? %>

<div id="error_explanation">

<h2>您输入的数据存在<%= pluralize(@user.errors.count, "") %> 处错误:</h2>


• <% @user.errors.full_messages.each do |msg| %>


• <%= msg %>
• <% end %>



</div>

<% end %>


7 自定义模型校验器

比如validate_presence_of方法 ,可以一次校验多个属性,比如

validate_presence_of(:name,:address......)验证多个属性非空


唯一属性:

validates_uniquencess_of(:name,:message=>"wrong")


例子:

class Account < ActiveRecord::Base

validates_presence_of(:name, :password, :message => "不能为空!")

validates_length_of(:name, :password, :within => 6..50, :message => "长度不合法")

validates_format_of(:name, :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/, :message => "格式错误!")

end


8 定义各种before,after的回调方法

def before_delete

.,,,

end


9 默认路由放在config文件夹下的route.rb中,路由类型

1) 默认的路由为route.rb中的最底部一行,即/controler/action/:id的形式

2) 资源路由

比如resouces:users

则同时生成7个不同的路由

_url方法:生成完整的URL绝对路径

_path:生成相对路径

比如users_url:生成http://localhost:3000/users

users_path 生成/users

:as选项

resources :users,:as =>"memebers"

指定了URL中使用members,但路由还是users

/members index

/members/new

resouces :users,:controller =>"members"

指定使用members 控制器


3)修改选项

可以重写选项,比如

map.resources :users,:path_name=>{:new=>'add',:edit=>'modi'}

只不过方法名变了

/users/add

/users/1/modi

4)path_prefix选项

增加一个前缀比如

resources :users, :path_prefix =>"/showrole/:user_id"

则变成

/showrole/1/users/

/showrole/1/users/2

5) resetful

resources :users,requirment =>{id= >/[A-Z][a-z][0-0]+/}

这个将会不会识别ID=1的数据

6)only产生指定的路由

resoucrs :photos,
nly =>[:index :show]

7)except指定哪个路由不被产生

resoucrs :users, :except =>:destory



10) 命名路由

match 'welcome',:to=>'users#index', :as=>'welcome'


创建了一个welcome的路由,调用user控制器的index方法。

11)嵌套路由

比如获得id=100的评论,该评论指向id=50的文章

/articles/50/comments/100

12) 正则路由

例子:

#实现查看指定日期的文章,例如 blog/articles/2011-02-14

# match 'blog/articles/:date' , :action=>'search', :controller=>'blog',

# :date=>/\d{4}-\d{2}-\d{2}/


#实现查看某一年的所有图片,例如photos/2011/all

# match 'photos/:year/all' ,:action=>'search' , :controller=>'photos' ,

# :year=> /\w{4}/


#实现查看某个关键字的所有文章,例如articles/show/rails

# match 'articles/show/:key' => 'articles#searchkey', :via =>
OST


#实现按编号查看某个分类下的所有文章,例如blog/index/1

# match 'blog/index/:category' =>"blog#index", :constraints => {:category => /\d/}


# 实现用户对某篇文章的管理操作,例如users/1/admin

# match 'users/:id/admin' => 'users#admin', :as => :admin


#实现用户登录后进入的页面

# match 'user/homepage/', :action=>'login', :controller=>'users' ,:defaults=>{:homepage=>'usercenter'}


14 actioncontroller的6个对象

1) sessions

session[:username]="sdsd"

获得#{session[:username]}

session[:username]=nil

2)params[:user][:name] 访问user类的name属性

3)request

4)response

5)renders

render :action=>"success" //使用success模版

6)redirects

redirect_to :action=>'show', :id=>@entry.id

返回到show的action,并指定id


15) 用户自定义控制器<<ApplicationController<<actioncontroller<<base

16) 自定义模版

def index

@users=User.all

render :action=>"list"

end

表示使用app\views\user下的list.htm.erb文件模版

17) 自定义layout模版

也可以用render :action=>"list",:layout=>"users"

//表示不使用app\views\layouts下的文件夹,而使用app\views\layouts下的新建立的

users.htm.erb文件


18 局部模版

以_开头的

render :partial=>"showuser"

局部模版开头以_showuser开头

19 内嵌模版

def inline

@users = User.all

render :inline=>"<h3>查看所有用户</h3>
1.
<% @users.each do |user| %>

2. <%=h '用户名:' + user.name %> [<%= user.department %>部门]
3. <%= user.phone %> <% end %>

"

end


20 :file 重复使用一个模版

render :file=>"d:/xxxxxxxxxxxxxxxxxxxxxx"

即将使用file指定的模版

def index

@books = Book.all

render :file=>"/books/cart",:layout=>true

end




21 render :text,将错误信息输出


def error

render :text=>'<h2>很抱歉,您要访问的页面不存在。</h2> <img src="/imgs/404.gif"> 您的访问出错了,时间: '+Time.now+'。


<br/>单击这里
​​返回首页​​。




',:layout=>true

end


22 重定向action

redirect_to :controller=>"user",:action=>"login"

redirect_to跳转页面时,可以指定控制器,render不行;

render可以指定模版,而redirect_to不可以指定模版



redirect_to "/books/1",:notice=>'xxxxxxxx'


23 过滤器

before,after,around(before,after都同时执行)


引用方式:

1) before_filter : abc

def abc

.........

end


2) before_filter{ |controler| }



3)过滤选项

如果父类有过滤器,则父类的过滤器也会应用于子类,先执行父类的,再执行子类的,

跳过所有过滤器 skip_before_filter跳过before,skip_after_filter跳过after,skip_filter跳过所有

过滤器



一个登陆过滤器的例子:

class BooksController < ApplicationController

before_filter :safecheck,:except=>[ :login ,:prologin]

def safecheck

if !session[:user_name].nil? then

@currentUserName=session[:user_name]

return true;

end

else

redirect_to "/books/login", :notice =>'对不起,你还没有登录。'

return false

end


except:出了login,prologin这两个action不进行过滤



def prologin

uname=params[:user][:name]

upass=params[:user][:pass]



if (uname=="admin")&&(upass=="admin") then

session[:user_name]=uname

session[:user_pass]=upass

redirect_to "/books/list", :notice => '欢迎回来,当前用户:'+session[:user_name]+',现在时间是:'+Time.now.strftime("%Y-%m-%d %H:%M:%S")+'。'

else

redirect_to "/books/login", :notice => '您的输入有误,登录失败。'

end



end



24 过滤器设置中文响应

class ApplicationController < ActionController::Base

protect_from_forgery

before_filter :changeCharset

def changeCharset

response.headers["Content-Type"]="text/html; charset=gb2312"

end

end

25 整个网站的index

删除public下的index.html文件,然后在routs.rb下加入

root :to=>"controller名#index"

举报

相关推荐

0 条评论