I'm new to Rails, Rails_Admin and Devise. Trying to get current_user, which I thought should be provided by Devise, in a model:
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
In Rails_Admin I get:
undefined local variable or method `current_user' for #<Item:0x007fc3bd9c4d60>
Same with
self.user_id = _current_user.id unless self.user_id
I saw there's a line in config/initializers/rails_admin.rb but not sure what it does:
config.current_user_method { current_user } # auto-generated
current_user doesn't belong to model. This answer has some explanation.
Rails 3 devise, current_user is not accessible in a Model ?
You can't refer to current_user in the models because it is only available to Controllers and Views. This is because it's defined in ApplicationController. The way to get around this is to set the user attribute on Item when you create it in the controller.
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
Additionally to make sure your Item isn't saved without the user attribute set, you can put a validation on the user_id. If it isn't set, the Item won't save to the database.
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
The validation in essence solves what you were trying to do when you were setting user in the model with the after_initialize callback. A guarantee that the Item isn't saved without that information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With