欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ruby on rails 入门注意事项 2

程序员文章站 2022-03-25 09:12:37
...

参考前一篇博客:

 http://hw1287789687.iteye.com/blog/2288230

(7)更新记录(保存更新)

我的写法:

 

def update

    articles = Article.update(params[:id], params.require(:article).permit(:title, :text))
    redirect_to :action => 'list'
  end

  最佳实践:

 

 

def update
    @article = Article.find(params[:id])
    @article.update(params.require(:article).permit(:title, :text))

    redirect_to :action => 'list'
  end

 先通过id查询记录,然后再更新,而不是直接更新

 

(8)手动指定视图

 

render template: "articles/show"

  类似于springMVC中的:
ruby on rails 入门注意事项 2
            
    
    博客分类: ruby rubyonrailsrender 
 等价于:

render :show

下面的方式达到的效果是完全相同的: 

render :edit
render action: :edit
render "edit"
render "edit.html.erb"
render action: "edit"
render action: "edit.html.erb"
render "books/edit"
render "books/edit.html.erb"
render template: "books/edit"
render template: "books/edit.html.erb"
render "/path/to/rails/app/views/books/edit"
render "/path/to/rails/app/views/books/edit.html.erb"
render file: "/path/to/rails/app/views/books/edit"
render file: "/path/to/rails/app/views/books/edit.html.erb"

 

 

 

 

(9)浏览器跳转

使用redirect_to

 

# 增加,持久化到数据库
  def create
    articles = Article.create(params.require(:article).permit(:title, :text))
    # render plain: params[:article].inspect
    redirect_to :action => 'list'
  end

 类似于spring MVC中的

response.sendRedirect

ruby on rails 入门注意事项 2
            
    
    博客分类: ruby rubyonrailsrender 
 

 

 

(10)CRUD

增:

Article.create(params.require(:article).permit(:title, :text))

 

删除:

id=params[:id]
    Article.find(id).destroy;

 

改:

@book = Book.find(params[:id])
@book.update(book_params)

 

条件查询

@article=Article.find_by(id: id)

 

查询所有

@articles=Article.all

 

(11)指定请求方式

使用method

<%= form_for :article, method: "PUT", url: {action: "update"} do |f| %>

 (12)rubyonrails中好像没有Java Web中的forward跳转

知道在rails中forward跳转的同学麻烦告诉我下

(13)构造表单时推荐使用form_for

we used form_for tag for the form action. It will perform better than form_tag. Why because it will create interaction with the Model easily. Therefore it is better to use form_for tag whenever you need interaction between the model and the form fields.

翻译:

我们使用form_for实现表单提交.它比form_tag 更强大.为什么呢?

因为form_for 可以更方便地与Modeal进行交互(数据绑定).

因此,无论什么时候,你需要在model和表单之间进行数据传递时推荐使用form_for.

 参考:

http://www.tutorialspoint.com/ruby-on-rails/rails-controllers.htm

http://guides.rubyonrails.org/layouts_and_rendering.html

http://www.tutorialspoint.com/ruby-on-rails/rails-views.htm

 了解更多:ruby on rails 入门注意事项 3

  • ruby on rails 入门注意事项 2
            
    
    博客分类: ruby rubyonrailsrender 
  • 大小: 86.8 KB
  • ruby on rails 入门注意事项 2
            
    
    博客分类: ruby rubyonrailsrender 
  • 大小: 23.1 KB
相关标签: rubyonrails render