Rails设计访问控制器中current_user的问题

时间:2015-05-22 22:14:58

标签: ruby-on-rails devise

我正在使用Devise进行身份验证的Rails和Angular应用程序。我在控制器index操作中访问current_user时遇到问题。

我需要显示属于特定用户的列表。

class ListsController < ApplicationController
  respond_to :json
  before_filter :authenticate_user!

  def index
    respond_with current_user.List.all
  end

  def create
    respond_with List.create(list_params.merge(user_id: current_user.id))
  end

 end

当我转到索引时,会返回no方法错误:

Started POST "/users/sign_in.json" for ::1 at 2015-05-22 18:08:20 -0400
Processing by Devise::SessionsController#create as JSON
  Parameters: {"user"=>{}, "session"=>{"user"=>{}}}
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Completed 201 Created in 37ms (Views: 1.5ms | ActiveRecord: 2.9ms)


Started POST "/users/sign_in.json" for ::1 at 2015-05-22 18:08:20 -0400
Processing by Devise::SessionsController#create as JSON
  Parameters: {"user"=>{}, "session"=>{"user"=>{}}}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Completed 201 Created in 14ms (Views: 1.6ms | ActiveRecord: 0.3ms)


Started GET "/lists.json" for ::1 at 2015-05-22 18:08:20 -0400
Processing by ListsController#index as JSON
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Completed 500 Internal Server Error in 7ms

NoMethodError (undefined method `List' for #<User:0x007fdb5bc37a10>):
  app/controllers/lists_controller.rb:6:in `index'

如果我更改&#39;索引&#39;对List.all的操作,它将返回所有用户的列表。我只需要访问特定用户的列表。

这是我的列表模型:

class List < ActiveRecord::Base
    belongs_to :user
    has_many :words, dependent: :delete_all

    def as_json(options = {})
        super(options.merge(include: :words))
    end
end

1 个答案:

答案 0 :(得分:3)

您应该使用小写名称 - dir="rtl"。约定list(大写单词) - 是类的名称(最终在你的情况下 - 模型),而不是属性的名称。

请注意,如果用户模型与List模型相关联 - 您可以像

那样执行这些操作
List

指定关联记录时不需要# if there is a like in user.rb has_many :lists # you can use in your controller current_user.lists 。这是guide

相关问题