我有一个 Ruby on Rails 源代码,现在我想解析数据并发送数据。在我的代码中,它将从用户获取名称并显示它,如何解析 ROR 中的数据。
这是我的controller.rb代码
def index
@hotels = Hotel.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @hotels }
end
end
# GET /hotels/1
# GET /hotels/1.json
def show
@hotel = Hotel.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @hotel }
end
end
# GET /hotels/new
# GET /hotels/new.json
def new
@hotel = Hotel.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @hotel }
end
end
# GET /hotels/1/edit
def edit
@hotel = Hotel.find(params[:id])
end
# POST /hotels
# POST /hotels.json
def create
@hotel = Hotel.new(params[:hotel])
respond_to do |format|
if @hotel.save
format.html { redirect_to @hotel, notice: 'Hotel was successfully created.' }
format.json { render json: @hotel, status: :created, location: @hotel }
else
format.html { render action: "new" }
format.json { render json: @hotel.errors, status: :unprocessable_entity }
end
end
end
# PUT /hotels/1
# PUT /hotels/1.json
def update
@hotel = Hotel.find(params[:id])
respond_to do |format|
if @hotel.update_attributes(params[:hotel])
format.html { redirect_to @hotel, notice: 'Hotel was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @hotel.errors, status: :unprocessable_entity }
end
end
end
# DELETE /hotels/1
# DELETE /hotels/1.json
def destroy
@hotel = Hotel.find(params[:id])
@hotel.destroy
respond_to do |format|
format.html { redirect_to hotels_url }
format.json { head :no_content }
end
end
如何使用Json解析ROR中的这些数据如何编写解析这些数据的 json 文件,如何做到这一点
**Answer of my question**
这部分我们必须在控制器中完成
酒店控制器.erb
respond_to :json, :xml
def index
@hotels = Hotel.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: @hotels.to_json(:only => [ :id, :name ]) }
end
end
查看/index.json.erb
[
<% @hotels.each do |hotel| %>
{ 'id': <%= hotel.id %>, 'name': "<%= hotel.name %>" },
<% end %>
]
路线.rb
get 'hotels' => 'hotels#index', :as => 'hotels'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)