那些rails的第一道坎

问题:

ActionController::InvalidAuthenticityToken in Admin::ProductsController#create


解决方法:

在对应的Controller中加入skip_before_action :verify_authenticity_token



问题:

在REST服务中,是没有后缀的情况下时,没有办法匹配到Resource


解决方法:

class Product < ActiveResource::Base
self.site = "http://localhost:8080/"
  self.include_format_in_path = false
end



问题:

undefined method product_path:


解决方法:

http://stackoverflow.com/questions/8706774/undefined-method-with-path-while-using-rails-form-for

  get 'products/' => 'products#index'

  get 'products/:id' => 'products#show', :as => :product

  这样以后就可以使用类似product_path(@product)的方法来获取product对应的路径了



问题:

我们如何POST一个ActiveResource


解决方法:

http://apidock.com/rails/ActiveResource/Base



问题:

使用了ActiveResource来访问第三方提供的REST API,form_for(@product)的时候,会出现@product的错误提示信息


解决方法:

这是因为Rails本身并不知道你的Product这个Resource的定义,所以,方法就是自己写一个原始的HTML。但这里有另外一个问题需要我们注意,就是,我们在ProductsController里面创建或修改product的时候有这样的代码:

   def product_params
      params[:product]
   end

表示获取Product这个对象,而我们看到这里要求的是product作为key,这就要求我们自己写的HTML类似于这个样子:

<input id="product_title" name="product[title]" type="text">


这样在params[:product]中就有了title这样一个属性



问题:

ActionController::UrlGenerationError in Admin::ProductsController#create

No route matches {:action=>"show", :controller=>"admin/products", :id=>nil} missing required keys: [:id]

 
 
if @admin_product.save
redirect_to admin_product_path(@admin_product)
end

解决方法:

redirect_to admin_product_path(@admin_product.id),应该还有其他更好的解决办法吧



问题:

如何定义Subresource


解决方法:

require 'rubygems'
require 'active_resource'


class Pricing < ActiveResource::Base
self.site = "http://localhost:8080/products/:product_id"
  self.include_format_in_path = false

  belongs_to :product
end


class Product < ActiveResource::Base
self.site = "http://localhost:8080/"
  self.include_format_in_path = false


  has_many :prices
end


问题:

如何测试Subresource

解决方法:

class Admin::PricesControllerTest < ActionController::TestCase
 
  test "should get index" do
    get(:index, {:product_id => 1})
    assert_response :success
    assert_not_nil assigns(:admin_prices)
  end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值