Learn Rails5.2- Scaffolding and REST,flash.now, flash.keep; Access via JSON

用generator建立一个手脚架

Representational State Transfer (REST).  具像的状态转存。

https://en.wikipedia.org/wiki/Representational_state_transfer 

RESTful风格的简单的理解:

如何根据一个简单的法则来存取数据。法则包括CRUD的原理和对HTTP的明确定义。 


redirect_to

logger.info "+++ Example +++"  :可以添加log,同时在terminal上显示。 

redirect_to :back  :回到刚才的页面。


Flash Messages 

在Rails, Flash Messages就是在redirect后,显示在新的网页上的提示。redirect_to和它一起使用。redirect_to(options = {}, response_status_and_flash = {})

ActionDispatch::Flash Object

这个模块又包含2个模块:

1. RequestMethods, flash()和flash=(flash), reset_session()3个方法。

2. FlashHash, 这个模块包含了大量对flash对象的实例方法 

[](k), []=(k, v),  和由此演化出的alert(), notice(), 如此便可以使用flash[:alert] 

⚠️ 除了alert,notice,可以使用任意的key,原理是[],[]=。但是和redirect_to在一行使用的话,只能使用alert或notice 

each(&block) , empty?

keep(k = nil)

一般情况,在一个action中新增的flash,会用在下一个request行为,然后删除。如果希望这个flash保留起来,在下下个request中还能使用。则使用keep方法。 

如flash.keep会保留整个flash给下一个request。也可以指定flash.keep(:notice)

案例:从某个request行为redirect到index.html.erb页面的flash不会消失,它还会在users_url中使用一次。 

  def index
    flash.keep
    redirect_to users_url
  end

now()

flash.now[:message] = "Hello current action"。 当你需要传递一个flash对象给当前的action时,使用now方法,你的对象会在当前action完成后消失。

默认,新增values给flash会让它们在下一个request中使用。但是有时候想要使用它们在同一个request中。比如当create行为失败了,你会直接render新的模版,这不会发出新的请求,但你仍然想要显示一个flash信息。此时,你可以使用flash.now方法。

  def create
    @client = Client.new(params[:client])
    if @client.save
      # ...
    else
      flash.now[:error] = "Could not save client"
      render action: "new"
    end
  end

在视图页面可以这么写:

    <% flash.each do |name, message| %>
      <p><i><%= "#{name}: #{message}" %></i></p>
    <% end %>

Scaffold的摘录

Access via JSON 

默认,Rails's的生成器不仅仅为了人类用户通过HTML进行存取操作,也为机器准备了一个直接的接口。相同的action可以通过这个接口调用。

https://zh.wikipedia.org/wiki/JSON 

JavaScript Object Notation or JSON 

轻量级数据交换语言,用来传输由属性值或者序列性的值组成的数据对象。它脱胎于JavaScript。JSON官方类型是 application/json, 扩展名.json

gem "jbuilder" 。

JSON As Default 

 index.json.jbuilder

json.array! @products, partial: "products/product", as: :product

解释:渲染了partial _product.json.jbuilder

json.extract! product, :id, :name, :price, :created_at, :updated_at

json.url product_url(product, format: :json) 

在浏览器里输入http://localhost:3000/products.json 

JSON and XML Togethe 

 手脚架没有生产index动作的JSON格式。

  def index
    @products = Product.all
    respond_to do |format|
      format.html
      format.json {render json: @projects}
      format.xml {render xml: @products}
    end
  end

 什么时候使用Scaffolding?

任何时候都不要使用手脚架,Rails developer都是手动建立每件东西。

不过在快速开始一个新project的时候还有用,仅仅是在开始。 

也可以新建一个scaffold然后删除不需要的部分。

rm app/views/products/*.jbuilder.json

把router.rb中的resources :products加上only:[:index]的限制。

controller 中删除没有用的action。

在index.html.erb,show.html.erb中删除无用的link_to 


原文地址:https://www.cnblogs.com/chentianwei/p/9192963.html