Validate using an existing value
I have a Topic model:
class Topic < ActiveRecord::Base
belongs_to :user
def validate_on_update
errors.add(:user, "Only the topic creator can update the topc") if
self.user != user;
end
end
I would like to check before every update that the existing topic.user is the same with the user that is trying to update the model.
I think that
self.user != user
is not working but I do not k开发者_JAVA百科now how to fix that!
You need to find the record in the controller before doing that, so you can do this in your controller action:
@topic = current_user.topics.find(params[:id])
This will trigger an exception that you can easily catch or leave it.
This is the best method to ensure data integrity, unless you're tinkering in other places of the app and you need to create Topics not in controllers.
If you have such need, it's not bad to have a validation rule in the model to ensure major data integrity, but the model does need to know the user, that's only accessible from the controller.
My recommendation is that you assign the user controller-side or just use scopes like:
current_user.topics.create(params[:topic])
This way you are sure that the user is the same in question, and this invalidates the need to do another validation if it's the only place you're calling topic creation.
If you are unsure and wants to game on with a validate_on_update I suggest creating a virtual attribute like so:
attr_accessor :this_user
But in any case you'd pass this via controller, since your model should know nothing about the current logged in user:
@topic = Topic.new(params[:topic])
@topic.this_user = current_user # or @topic.user_id and check for a attr_changed?
Update: adding example as requested
# @topic = Topic.new(params[:topic])
# @topic.this_user = current_user
class Topic < ActiveRecord::Base
belongs_to :user
attr_accessor :this_user
def validate_on_update
# Make sure that this_user is an instance of User, otherwise just use the id
errors.add(:user, "Only the topic creator can update the topic") if user_id != this_user.id;
end
end
Update:
another suggestion is to use:
attr_readonly :user_id
精彩评论