这个Rails路由约束有什么问题?

时间:2017-07-13 11:07:40

标签: ruby-on-rails routing constraints

我正在尝试编写一个路由约束,该约束依赖于设备用户的嵌套资源的存在。

User has_one Company, Company belongs_to User.
Company has_many Quotes, Quote belongs_to Company.

我想root如下;

root 'quotes#new', contraints: CompanyPresentConstraint.new
root 'companies#new'

我有app / contraints / company_present_constraint.rb;

class CompanyPresentConstraint
    def current_user(request)
      User.find_by_id(request.session[:user_id])
    end

    def matches?(request)
        user = current_user(request)
        user.company.present?
    end
end

有公司的用户,GETing'/'被路由到引号#new很好,但是没有公司的用户仍然被路由到引号#new,并且由于@company对象不可用而失败嵌套的form_for,尽管routes.rb指定没有公司存在应该路由到公司#new,如上所述。

我知道约束似乎失败的原因是我的引用#new视图有; %= simple_form_for [@company,@quote] do |quote| %>当以我知道没有公司的用户身份登录时,给出的错误是undefined method 'quotes_path' for #<#<Class:0x007fb455cf9c78>:0x007fb453c2c478>,这表明尽管该用户没有公司,但他们仍然被路由到报价#new

我不确定问题出在哪里,有人可以指出吗?

由于

针对性;

  • 在任何情况下根网址到引号#new,因此#matches?一定不能按预期运行?
  • 所有控制器和路由必须设计为user_authenticated。
  • 当没有公司的用户被路由到引号时会发生什么#new是要求@company和@quote对象的嵌套表单失败,如上所述。

思路:

  • 约束是否在正确的位置并自动加载?
  • #matches?正在做我想做的事吗?即检查通过session[:user_id]找到的用户的公司存在?在评论中提出的好处是约束是“预路由”,因此路由控制器#action没有提出设计user_authentication,因此会话可能不可用。但是,尽管如此,routes.rb仍然会将root发送到quotes#new而不是comapnies#new,因为它无法从#matches?返回true。

0 个答案:

没有答案