Hi friends,
There are some special kinds of methods in active records rails, that can be used for different purposes. Here I am explaining two of them
1. none method:
none method as its name suggests returns no records. So it is used in the case where you do not want to return any records to a specific user. Suppose a user is blocked and he looks for blogs in that case we can use the none method so that he doesn't get any record. It either returns empty array [] or nil.
def get_blogs
if user.is_blocked?
Blog.none
#=>
Will return 0 records or you can say empty array []
else
Blog.all
end
end
# Here get_blogs is a method to retrieve the blogs and is_blocked checks whether the user is blocked or not
2. readonly method:
In some cases you might want the object to be available in read only mode so that they are available only for reading purpose and not for modifications. In that case readonly method is used, which returns the object in read-only mode. If any modification is tried to be made it throws ActiveRecord::ReadOnlyRecord exception.
blog = Blog.readonly.first
blog.title = "New Title"
blog.save
#=> ActiveRecord::ReadOnlyRecord: Blog is marked as readonly
Hope you liked reading it.
0 Comment(s)