So first I had this class:
class User < ActiveRecord::Base
attr_accessible :email, :name
end
and was able to create and save users in ruby sandbox.
Then I added validation like this:
validates(:name, presence: true)
saved my changes, went back to console, and said this:
>> user = User.new(name: "", email: "mhartl#example.com")
>> user.save
It should return FALSE because name is blank. But it returned true. Why?
Maybe I should restart the sandbox console?
Try doing:
reload!
in the console.
This will reload your models and should pick up the new validation. This makes it unnecessary to restart the console. I use this like a bajillion times a day. :D
Yes never mind. I restarted the sandbox console and now validation is working correctly.
Related
I found something which seems a bit confusing to me being new to Rails. I was told I need to do reload! in the console whenever I made a change in the model.
Let's assume I call reload! before these two senarios.
Let's say I have scenario A, with a model with a specific syntax error as such:
class Article < ActiveRecord::Base
validator :title, presence: true
end
Running Article.new(title: "Test 1") will throw a NoMethodError, as it understandably would. But if I then go in and fix the error, even if I don't run reload!, running Article.new(title: "Test 1") works now.
Scenario B, going in the opposite direction. I have a model with the correct syntax as such:
class Article < ActiveRecord::Base
validates :title, presence: true
end
Running Article.new(title: "Test 1") will work with no error, as it should. But if I then go in and change validates to validator. If I don't run reload!, running Article.new(title: "Test 1") still works despite the article.rb file having a syntax error. It isn't until I run reload! explicitly that I now get a NoMethodError.
What's exactly going on here? I know it's very specific, but I don't see why this would be the case. It seems like sometimes you have to run reload! to update the model (like scenario B) and sometimes, like in scenario A, you don't.
In your first example, Rails was not able to load the class because it raised an error. After fixing the error there was no need to class reload because the class was not loaded successfully before.
In your second example, the class was loaded successfully. Therefore you need to call reload! to tell Rails to reload the class into memory.
I have a model "User" that up until now didn't have any issues. I added some validations and noticed that I no longer could add any new Users - the record would be rolled back. So I removed the validations, but my records were still being rolled back. So I eliminated literally all the code from my model file so all it contains is this:
class User < ActiveRecord::Base
end
but I'm still getting the same error.
In my rails console:
> User.create(name: "test")
(0.6ms) BEGIN
(2.3ms) ROLLBACK
#=> #<User id: nil, name: "test", (et cetera)>
I don't even know how to start figuring out what's wrong. How can I even debug this? All my other models work normally.
This is what I added before this started:
blacklist = ['home'].freeze
validates :name, exclusion: {in: blacklist}
SOLVED:
I integrated Devise with this model, so there were some validations in place that weren't in my Devise.rb file. I had to run #user.errors to get back the errors that were preventing the record from being saved.
Try this:
user = User.new(name: "test")
user.save
user.errors # This should contain the errors that prevented your object from being saved.
I noticed that one of my model fields would not update through my app in the browser after it had been initially set. When I went to investigate this I discovered that the field was only declared through a custom validator:
validate :amount_validator
def amount_validator
if self.amount == nil
errors.add(:amount, "Please fill in the amount.")
end
end
I thought the issue was that this was missing:
validates :amount, presence: true
I added this but I still couldn't update the field through the browser. When I saved the value and the page refreshed it had reverted to its original value. I read another SO question that indicated I should try updating this field through the console and see if there were any errors. I did this, it worked with no errors. Went back into the browser and the value had changed but I still could not update it through the browser. Thanks for your help.
Depending on what rails version you're using, the error might be around accessible attributes (Rails 3) or strong paramenters (Rails 4).
On Rails 3, make sure that you have this in your model:
attr_accessible :amount
On Rails 4, make sure that you are allowing the attribute in the hash that you pass to update_attributes in your controller:
your_model.update_attributes(params.require(:your_model_name).permit([:amount]))
class User < ActiveRecord::Base
attr_accessible :email, :name
validates :name,:presence=>true,
:length=>{:maximum=>15}
validates :email,:presence=>true,
:length=>{:maximum=>15}
end
I am new to rails and the simplest of the validators are not working. I think I may be making a very silly mistake . I have a User model with 2 attributes only and when I create a new user in ruby console with wrong validations like no name or a longer name than 15 characters it gets added happily Please suggest.I am using rails version:3.2.13 and ruby version:1.9.3
If you are on rails console, be sure to type reload! after making changes to models. In this way, all changes will be reloaded in the console instance.
Moreover, are you sure you are saving these models? You should try something like this:
user = User.new(email: "john.doe#gmail.com")
user.save
If the result of the last line is false, you can view the validation errors with
p user.errors
I am new to ROR and been trying to fumble my way through the tutorial by mike hartl( excellent read for starters i might add ). There is however something i am struggling with, my user model looks like below.
class User < ActiveRecord::Base
validates :name , :presence => true, :length => {:maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => true
end
I then open the ruby console using rails -c and create a new user
usr = User.new(:name=>"abcd",:email=>"svsvenu#gmail.com")
I then save it by using
usr.save
This created a new record in my database. So far so good.but if i type
usr.save
again, nothing happens, i look at the database ( sqlite ) and not even the last update date changed.
Another interesting thing i noticed is when i use
User.create(:name=>"abcd",:email=>"svsvenu#gmail.com"),
multiple times, there is a record created every time i run it in the console.
Can some one please explain why my save does not work and also why my uniqueness constraint is being ignored?
Thanks in advance
ActiveRecord is smart enough to understand that when you type usr.save twice in a row, the 2nd one is redundant.
usr = User.new
usr.save # usr is saved (if it was valid)
usr.save # usr is already saved and unchanged! do nothing.
usr.name = "bananas"
usr.save # usr name changed, commit the change!
When you say that a user is created in the console each time you run User.create, are you sure they're actually being created? In console you'll see a User returned each time, but the id would be nil if there had been errors in the create attempt. If you run create! instead you'd see an exception if the User had validation errors (like a duplicate email) and did not save.