I am new to rails. I want to know the best way to handle inputs errors in rails. Using :message in validates_format_of method then checking in the views the value of the hash or initializing the model with a ActiveModel::Errors.new, and then using it in the views (passing in the model attr_reader :errors), or other any way ?
I use :messageĀ invalidates_format_of methodĀ then checking in the views, This is a universal practice
The guide http://guides.rubyonrails.org/active_record_validations_callbacks.html#error_messages-and-error_messages_for
A good way to validate input errors is to have both client-side and server-side validations. You can rely on Rails validators on your models, and on the front end you can either use the newer HTML elements, javascript, or a combination of both.
With regards to Rails validations specifically, I don't think you need to stray too far from the conventions. Obviously if you need a different strategy you can definitely incorporate it, but at that point I would definitely suggest adding tests (which is not something I typically do for Rails validations).
Related
guys! I'm trying to make right architecture decision:
I need to hide from user of my site some fields of other users by default. So not to bother with filtering the fields in views I want to not load those fields at all, like:
default_scope -> { select(column_names - FILTERED_PARAMS) }
the rest of fields should be loaded explicitly in special cases.
The problem is that once code refers to the missing fields nomethod error shows up. I tried to meta-program those fields but fruitless this far. It seems to me that this approach doesn't fit to the AR object life-cycle.
Have you ever implemented such functionality if so what pattern have you chosen?
From my experience the best decision would be not to filter these params on the query with select, but to filter what parameters are actually sent to the user. my_model.as_json (with given param filtering options) is a simple solution for that, but for more advanced uses I would advise Rabl gem
https://github.com/nesquena/rabl
That way you have more control over which params are returned even in very advanced cases in a model-view-controller manner.
How much of this is auto-generated methods in Rails "User.find_or_create_from_auth_hash(auth_hash)". That is just wondering how this works, and what would have been the minimum coding the dev would have to do? That is, what method would they have had to implement in the User model? or would they need a method named exactly that. So just wondering if the "find", "create", "from" keywords are Rails specials here.
Taken from here: https://github.com/intridea/omniauth
Rails provides the dynamic finders find_by_*, find_or_initialize_by_*, and find_or_create_by_* via method_missing for each attribute of your model.
The self.find_or_create_from_auth_hash(auth_hash) method however isn't at all provided by rails and is simply using the same type of naming conventions for readability.
EDIT:
Apparently it also provides find_last_by_* and find_all_by_* as well. I've personally never used them though.
I am using Ruby on Rails 3 and I would like to know if my approach to validate new record is good or not.
I don't use the common RoR validation system, so in my model I have all custom validation mathods like these:
def validates_user_name(user)
...
end
def validates_user_surname(user)
...
end
...
that I call from controller in this way
def create
...
#user.validates_user_name(params[:user])
#user.validates_user_name(params[:user])
...
end
Is it a good way to validate the creation of new user? There will be problems with hackers using this approach?
I think you're going to have a hard time convincing anyone that your custom validations are better than what's built into Rails, especially if the validation logic is similar.
If you still want control over when things happen, you should take advantage of the built-in callback hooks like before_create. There are lots of advantages of doing it this way, including automatic transaction rollback and decoupling. However, if what you're doing is already accomplished by Rails, it's not advisable to reinvent the wheel.
I'm building a model, which whenever the model is run I want to inject into a news feed model. My idea was to create a after_save in the model and then use a helper to populate the feed details. But my model isn't finding the helper...
Now I'm wondering, what are helpers for, are helpers really just for Views or?
In my model I want to run stuff like:
newsfeed.feeded_id = record.id
newsfeed.feeded_type = record.class.name
Which is common to many models in my app. Where should that live, and how should that be accessed? Thanks
Helpers are primarily for views. They allow you to keep your code out of the views and make a testable chunk of code that can be used when rendering the view. It also allows you to reuse bits of code.
I don't think there are any rules of thumb, but if you use the exact same bit of view code more than once, consider abstracting it into a partial. If you have any complicated conditionals or calculations, consider placing it in a helper.
As an example of what's good to put in helpers, you need look no further than Rails itself. Perfect examples are link_to, form_for, etc. These take a bit of doing to construct but provide way more functionality than writing the HTML from scratch each time.
How about using an observer?
Are you setting up your news via RSS/ATOM? Your builder view might be a place to select what items you want in your feed.
I want to have a site that is a simple blog so I created a model:
class Post < ActiveRecord::Base
attr_accessible :title, :body
end
I want to use Markdown but without HTML tags. I also want always to keep database clean and my idea is to use before_save()/before_update() callbacks to sanitise my input and escape HTML.
I don't care about caching and performance therefore I always want to render post when needed. My idea is toadd following to the model:
def body_as_html
html_from_markdown(body)
end
What do you think of such design? MVC and ActiveRecord are new for me and I am not sure of used callback.
I see nothing obvious wrong with that method. Caching is a very simple thing to enable if performance becomes an issue... the important thing to make caching useful is to reduce or eliminate the dynamic content on the page, so that the cache doesn't constantly get obsolete. If you're just showing the blog post, then the cache only needs to be regenerated if the blog changes, or perhaps if someone adds a comment (if you have comments).
My general rule of thumb is to keep the data in your database as "pure" as possible, and do any sanitization, rendering, escaping or general munging as close to the user as possible - typically in a helper method or the view, in a Rails app.
This has served me well for several reasons:
Different representations of your data may have display requirements - if you implement a console interface at some point, you won't want to have all that html sanitization.
Keeping all munging as far out from the database as possible makes it clear whose responsibility it is to sanitize. Many tools or new developers maintaining your code may not realize that strings are already sanitized, leading to double-escaping and other formatting ugliness. This also applies to the "different representations" problem, as things can end up escaped in multiple different ways.
When you look in your database by hand, which will end up happening from time to time, it's nice to see things in their un-munged form.
So, to address your specific project, I would suggest having your users enter their text as Markdown and storing it straight in to the database, without the before_save hook (which, as an aside, would be called on creation or update, so you wouldn't also need a before_update hook unless there was something specific that you wanted on update but not creation). I would then create a helper method, maybe santize_markdown, to do your sanitization. You could then call your helper method on the raw markdown, and generate your body html from the sanitized markdown. This could go in the view or in another helper method according to your taste and how many different places you were doing it, but I probably wouldn't put it in the model since it's so display-specific.