导轨中的路由无效

时间:2015-08-29 13:22:12

标签: ruby-on-rails ruby-on-rails-3 devise

我使用了devise gem进行身份验证。在我使用相册模型的同一个项目中。但我的new_user_album_path给出了错误。我认为有用户ID问题。请帮助我。

这是index.html.erb文件

<%= link_to 'New Article', new_user_album_path() %>
<table>
<tr>
 <th>Title</th>
<th>Description</th>
 </tr>

  <% @albums.each do |album| %>
  <tr>
  <td><%= album.title %></td>
    <td><%= album.description %></td>
  <td><%= link_to 'Show', user_album_path(album.user,album) %></td>
 <td><%= link_to 'Edit', edit_user_album_path(album.user,album) %></td>
  <td><%= link_to 'destroy', user_album_path(album.user,album),
    method: :delete,
    data: { confirm: 'Are you sure?' } %></td>
   </tr>

   <% end %>
   </table>



     this is albums_controller file

   class AlbumsController < ApplicationController
     before_action :authenticate_user!

   def index
    @albums = current_user.albums.all

       end

        def show
         @album = current_user.albums.find(params[:id])
       end

    def new
    @album = current_user.albums.new
   end

    def edit
    @album = current_user.albums.find(params[:id])
    end

   def create

   @album = current_user.albums.build(album_params)
   if @album.save
   redirect_to action: 'index'
   else
      render 'new'
   end
  end

     def update
    @album = current_user.albums.find(params[:id])

      if @album.update(album_params)
      redirect_to action: 'show'
      else
      render 'edit'
      end
     end

     def destroy
      @album = current_user.albums.find(params[:id])
      @album.destroy
     redirect_to action: 'index'
     end
    private
    def album_params
      params.require(:album).permit(:title, :description, :user_id)
    end

   end

   it is giving following errror.->


       NoMethodError in Albums#index



    undefined method `users' for nil:NilClass

    Extracted source (around line #2):

       <h1>Your Albums</h1>
    <%= link_to 'New Article', new_user_album_path(@album.users.id) %>
       <table>
       <tr>
          <th>Title</th>
        <th>Description</th>

route.rb file

    devise_for :users
   # The priority is based upon order of creation: first created priority.
 # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
   resources :users do
   resources :albums
   end

   root 'albums#index'

3 个答案:

答案 0 :(得分:1)

当路由设置正确时,应该出现以下问题:

new_user_album_path()

请求嵌套资源的路径,并且需要获取父对象,即您的用户:

new_user_album_path(user_id: current_user.id)

我认为即便如此:

new_user_album_path(current_user)

如果这不起作用, 您应该通过从shell调用

来检查路由是否与您认为的一样
rake routes 

在输出中查找new_user_album_path

  • 真的存在吗?
  • 所有名称部分的单数和复数是否相同?
  • 它需要什么参数?

答案 1 :(得分:0)

其他内容可能不正确,但在albums#index您定义了变量@albums,但在您的链接中使用了@album

更新

<%= link_to("New Article, new_user_album_path(@album.users.id)

<%= link_to("New Article, new_user_album_path(@albums.users.id)

收到不同的错误。对您的目标做一点解释会有所帮助。 :)

答案 2 :(得分:0)

请改为:

malloc()