【问题标题】:No matching route in Rails 4Rails 4中没有匹配的路线
【发布时间】:2016-07-16 10:05:32
【问题描述】:

我有一个User 模型,它属于userhas_many shiftsShift 模型。我试图弄清楚为什么会出现无路由匹配错误。

routes.rb:

get 'users/:id/shifts' => 'users#shifts', :as => :user_shifts 
resources :shifts

我创建了如下路线:

user_shifts GET    /users/:id/shifts(.:format)          users#shifts

我在导航视图中使用它来链接到如下页面:

<li><%= link_to "Shifts", user_shifts_path(@shifts) %></li>

在我的Users 控制器中:

def shifts
  @user = User.find(params[:id])
  @shifts = @user.shifts
end

用户/shifts.html.erb:

<% @shifts.each do |shift| %>
  <%= shift.start_time %>
<% end %>

错误:

No route matches {:action=>"shifts", :controller=>"users", :id=>nil} missing required keys: [:id]

但是当我手动输入网址http://localhost:3000/users/7/shifts 时,它可以工作吗?

我已经尝试了所有相关问题的答案,但似乎无济于事。有人可以帮忙吗?

追踪:

app/views/layouts/_nav.html.erb:24:in `_app_views_layouts__nav_html_erb__2914379975493970040_70146050606840'
app/views/layouts/application.html.erb:13:in `_app_views_layouts_application_html_erb___3858195360324705958_70145981089600'

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 url routes uri


    【解决方案1】:
    <li><%= link_to "Shifts", user_shifts_path(@shifts) %></li>
    

    这里@shifts 是一个对象。您需要在变量@shifts 中传递用户ID。 是这样的

    <li><%= link_to "Shifts", user_shifts_path(@user.id) %></li>
    

    【讨论】:

      【解决方案2】:

      你试过了吗:-

      user_shifts_path(:id=>@shifts)
      

      【讨论】:

        【解决方案3】:

        您应该使用以下内容:

        &lt;li&gt;&lt;%= link_to "Shifts", user_shifts_path(@user) %&gt;&lt;/li&gt;

        代替:

        &lt;li&gt;&lt;%= link_to "Shifts", user_shifts_path(@shifts) %&gt;&lt;/li&gt;

        user_shifts_path 期望 user

        更新:

        试试&lt;li&gt;&lt;%= link_to "Shifts", user_shifts_path(id: @user.id) %&gt;&lt;/li&gt;

        如果您遇到错误,请发布错误消息以及堆栈跟踪。

        【讨论】:

        • 不起作用我试过 ([@user, @shift]) 它消除了错误,但后来我收到了类似could notfind id的错误
        • undefined method id' for nil:NilClas我也更新了trace 不知道你是否需要完整的trace!
        • 确保您的@user 已设置action
        【解决方案4】:

        试试这个

        <%= link_to "Shifts", {:action=>"shifts", :controller=>"users", :id=>@user.id } %>
        

        <%= link_to "Shifts", user_shifts_path(id: @user.id) %>
        

        【讨论】:

        • undefined method id' for nil:NilClas 这两种方法
        • 这意味着来自 shifts 方法的 @user 为 nil。请检查并确保它不能为空。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        • 2017-07-13
        • 1970-01-01
        • 2015-11-08
        • 2018-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多