3

Rails、Rails_Admin、Devise は初めてです。モデルで、Devise が提供するはずだと思っていた current_user を取得しようとしています。

class Item < ActiveRecord::Base
  attr_accessible :user_id
  belongs_to :user, :inverse_of => :items

  after_initialize do
    if new_record?      
      self.user_id = current_user.id unless self.user_id
    end                                
  end  
end

Rails_Admin では次のようになります。

undefined local variable or method `current_user' for #<Item:0x007fc3bd9c4d60>

と同じ

self.user_id = _current_user.id unless self.user_id

config/initializers/rails_admin.rb に行があるのを見ましたが、それが何をするのかわかりません:

  config.current_user_method { current_user } # auto-generated
4

2 に答える 2

5

current_user はモデルに属していません。この答えにはいくつかの説明があります。

Rails 3 デバイス、モデルで current_user にアクセスできませんか?

于 2012-10-19T16:35:16.700 に答える
3

ControllersViewsでのみ使用できるため、モデルで current_user を参照することはできません。これは、ApplicationControllerで定義されているためです。これを回避する方法は、コントローラーでアイテムを作成するときにアイテムにユーザー属性を設定することです。

class ItemsController < Application Controller

  def create
    @item = Item.new(params[:item])
    @item.user = current_user # You have access to current_user in the controller
    if @item.save
      flash[:success] = "You have successfully saved the Item."
      redirect_to @item
    else
      flash[:error] = "There was an error saving the Item."
      render :new
    end
  end
end

さらに、ユーザー属性が設定されていないとアイテムが保存されないようにするために、user_id に検証を行うことができます。設定されていない場合、アイテムはデータベースに保存されません。

class Item < ActiveRecord::Base
  attr_accessible :user_id
  belongs_to :user,
             :inverse_of => :items # You probably don't need this inverse_of. In this
                                   # case, Rails can infer this automatically.

  validates :user_id,
            :presence => true
end

本質的に検証は、after_initialize コールバックを使用してモデルでユーザーを設定していたときに何をしようとしていたかを解決します。その情報がなければアイテムが保存されないという保証。

于 2012-10-19T16:20:29.207 に答える