Rails validation of non-model input - ruby-on-rails

I'm building an API with Rails 4.1. One of my calls takes 2 input fields and makes a call to a third party API to get more data. It then uses that data to make an ActiveRecord model.
How should I validate the input? I'm not making a model from the 2 input fields.
Note: They need to be validated before making the call to the third party API

From what you've written, I would say you want to look at attr_accessor and use ActiveRecord to validate your form data:
#app/models/model.rb
Class Model < ActiveRecord::Base
attr_accessor :your, :inputs
validates :your, :inputs, presence: true
end
This will create virtual attributes which you can then validate using the standard ActiveRecord validation functionality. I believe that, as your model will typically create instance methods for your datatable's attributes, you'll be able to achieve the same functionality with attr_accessor attributes
As mentioned by #Mohammed, you'll then be able to validate the inputs by creating an instance of the model with your data:
#app/controllers/your_controller.rb
Class Controller < ApplicationController
def create
#model = Model.new(input_params)
#model.valid?
end
private
def input_params
params.require(:model).permit(:your, :inputs)
end
end

Perhaps a form object would work for you: http://robots.thoughtbot.com/activemodel-form-objects

Are will these inputs be used as attibutes in the model? If so, why not initialise a new object and test for validity?
def new
foo = Foo.new(inputs)
foo.valid?
end
Otherwise you can use a plain old PORO that extends ActiveModel::Model module to imitate an AR model (validations and so forth). You can find more detail on this here: http://blog.remarkablelabs.com/2012/12/activemodel-model-rails-4-countdown-to-2013

Related

How to pass around model errors between multiple classes?

What's an elegant way to handle passing around model errors through chains of classes?
Let's say I have a complex form with inputs foo and bar for which I want to display validation errors on the form. However, foo and bar themselves are not model inputs, they are just data passed to service classes:
class ComplexForm
attr_accessor :foo, :bar
def save
foo_processor.process(foo)
bar_processor.process(bar)
end
end
The processors then validate the inputs, validate the resulting model, and either save or return errors. The processors use ActiveModel::Model
class FooProcessor
include ActiveModel::Model
validate :foo_is_valid
def process(foo)
model_instance = MyModel.new(parse(foo))
if valid? && model_instance.valid?
model_instance.save
else
???
end
end
end
How do I pass this potential chain of errors up to ComplexForm and attribute them to the right input?

How to add a virtual attribute to a model in Ruby on Rails?

I'm working on a RubyonRails/ActiveAdmin application. My RoR version is 4.2.5 and AA version is 1.0.0. I have a model Message as follows.
class Message < ActiveRecord::Base
belongs_to :user
validates :user, :content, presence: true
def palindrome
# return true/false
end
end
As you see, I want to have a read-only attribute palindrome which only depends on the content of message. I want this attribute to be treated exactly like a normal attribute. By normal, I mean when I retrieve messages via rails console or request json format of messages, I want to see a palindrome attribute in the list. I would also like to have a filter for message by this attribute.
I'm not sure how could I achieve this.
Ruby actually lets you create virtual attributes this way, which keeps you from having to manually create getter and setter methods:
attr_reader :palindrome #getter
attr_writer :palindrome #setter
attr_accessor :palindrome #both
You can also pass multiple arguments too:
attr_accessor :palindrome, :foo, :bar
The documentation for it isn't the greatest.
In your model, you can write attribute accessors (reader/writer) for your virtual attribute palindrome attribute this way:
# attr_reader
def palindrome
self[:palindrome]
end
# attr_writer
def palindrome=(val)
self[:palindrome] = val
end
# virtual attribute
def palindrome
#return true/false
end
And, as you are using Rails 4, you have to whitelist palindrome attribute like any other model attribute in your strong param definition inside your controller in order to able to mass assign the value of palindrome. Something like this:
# your_controller.rb
private
def your_model_params
params.require(:message).permit(:palindrome)
end
Take a look at this RailsCast on Virtual Attributes. Although, it's a bit old, but would be useful for concepts.
Note:
A virtual attribute will not show up in the param list automatically. But, you should be able to access it via Rails console like this: Message.new.palindrome. Also, you can expose this virtual attribute in your JSON API, for example if you are using Active Model Serializer, you can have: attribute palindrome in your MessageSerializer and then palindrome will be exposed to the JSON API.
Since Rails 5 you can also set virtual attributes like this:
attribute :palindrome, :boolean
It automatically casts the attribute to the specified type, which can be useful when the value comes from forms. This GoRails video shows some really good examples of both using the attr_accessor and the attribute approach. The documentation also includes some examples.

setting mandatory field automatically in Rails from Model callback, when and how?

I have this model which has a mandatory field which needs to be automatically set just before save. I'm struggling with the correct way to implement this:
build the logic in the controller before the save (and have validates rule in model)
build the logic in a before_save callback and have validates rule in model, but this seems to late in the flow? I do get validation errors this way.
build the logic in a before_save callback and don't define validation for this particular field
do it any of the ways above and don't assign a validates rule for the particular field
I was working on 2 since this seems like the correct way to implement this. Was considering the usage of before_validation, but I don't know what would happen when my other fields don't get validated... this could cause double assignment of the same value..
code for 2 which gives a basic idea of what I'm trying to achieve:
#category.rb
class Category < ActiveRecord::Base
before_create :set_position_number
def set_position_number
highest = Category.maximum(:position)
self.position = highest.to_i + 1
end
end
I'm struggling with the correct way to implement this
The most efficient way will be to use an ActiveRecord callback hook, such as you've posted:
#app/models/category.rb
class Category < ActiveRecord::Base
before_create :your_action
private
def your_action
#fires before create
end
end
but this seems to late in the flow
As mentioned in the comments, you can see the order of the callbacks (and thus their order in the flow):
Thus, if you want to populate some data before you validate, and then validate that data, you'll be best using the before_validation callback:
#app/models/category.rb
class Category < ActiveRecord::Base
before_validation :set_position_number, on: :create
validates :position, ______________
private
def set_position_number
highest = Category.maximum(:position)
self.position = highest.to_i + 1
end
end
Remember, a Rails model just populates certain attributes which are then to be either saved to the db, or validated. Rails does not care where those attributes come from; populating them before_validation is a good a source as the controller.
If you are setting a value automatically and don't take user input, you don't need validation. Write a unit test.
If the field is something like a position value, then you should indeed set it in a before_create callback.

Changing which Rails Validations run depending on current user in deeply nested form

I'm working with a nested form that encompasses a total of 7 models, each with different validations. When simply editing the form, the validations run and display fine, and data is saved properly. However, I need to have different validations run depending on who is submitting the form (ie, admins can skip some otherwise required fields).
I thought I could get certain validations to be skipped by using attr_accessible :editing_user in my models, then set this within the controller.
class ModelExample < ActiveRecord::Base
attr_accessible :editing_user
validates_presence_of :email, :unless => "editing_user == 'admin'"
end
class ModelExamplesController < ActionController::Base
def create
#model_example = ModelExample.new(params[:model_example])
#model_example.editing_user = 'admin'
#model_example.save
end
end
I used this basic structure within the nested models, checking to see if I could save properly. This is where the weird behavior starts. For some reason, it looks like ActiveRecord is trying to save nested models multiple times, running validations each time. What makes this odd is I call #model_example.save, which should just return false if it fails. But, the first validation goes through (since editing_user is set), but later validations fail and raise exceptions, so the normal .save methods ends up raising an exception instead of returning.
Does anyone know how to either avoid having ActiveRecord do all extra validations and saves, or how to persist editing_user across those duplicate actions?
ha! just did this yeasterday, well, almost same use case anyway (persist the user). Here is how i solved it (with all credit to my buddy Jason Dew that I copied from):
class User < ActiveRecord::Base
module ClassMethods
attr_accessor :current
end
extend ClassMethods
end
This code block adds a singleton accessor :current to the User class methods, and can be called as User.current. nicer looking that a method called self.currrent
then in the app controller
before_filter :require_user #=> which in this case goes off and sets the current_user var
before_filter {|c| User.current = current_user}
which passes the app controller to the block and sets the User.current var.
Then in any other model
class MyClass < ActiveRecord::Base
def log
"This was done by #{User.current}"
end
end

Difference between attr_accessor and attr_accessible

In Rails, what is the difference between attr_accessor and attr_accessible? From my understanding, using attr_accessor is used to create getter and setter methods for that variable, so that we can access the variable like Object.variable or Object.variable = some_value.
I read that attr_accessible makes that specific variable accessible to the outside world.
Can someone please tell me whats the difference
attr_accessor is a Ruby method that makes a getter and a setter. attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or update_attributes(attrs).
Here's a mass assignment:
Order.new({ :type => 'Corn', :quantity => 6 })
You can imagine that the order might also have a discount code, say :price_off. If you don't tag :price_off as attr_accessible you stop malicious code from being able to do like so:
Order.new({ :type => 'Corn', :quantity => 6, :price_off => 30 })
Even if your form doesn't have a field for :price_off, if it's in your model it's available by default. This means a crafted POST could still set it. Using attr_accessible white lists those things that can be mass assigned.
Many people on this thread and on google explain very well that attr_accessible specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time)
This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.
This is explained here on the official Rails doc : Mass Assignment
attr_accessor is a ruby code to (quickly) create setter and getter methods in a Class. That's all.
Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor in your model to create setters and getters in order to be able to modify your table's records.
This is because your model inherits all methods from the ActiveRecord::Base Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you.
This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")
Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :
SQL instructions :
CREATE TABLE users (
firstname string,
lastname string
role string
);
I assumed that you set the option config.active_record.whitelist_attributes = true in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment
Your Rails model will perfectly work with the Model here below :
class User < ActiveRecord::Base
end
However you will need to update each attribute of user separately in your controller for your form's View to work :
def update
#user = User.find_by_id(params[:id])
#user.firstname = params[:user][:firstname]
#user.lastname = params[:user][:lastname]
if #user.save
# Use of I18 internationalization t method for the flash message
flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
end
respond_with(#user)
end
Now to ease your life, you don't want to make a complicated controller for your User model.
So you will use the attr_accessible special method in your Class model :
class User < ActiveRecord::Base
attr_accessible :firstname, :lastname
end
So you can use the "highway" (mass assignment) to update :
def update
#user = User.find_by_id(params[:id])
if #user.update_attributes(params[:user])
# Use of I18 internationlization t method for the flash message
flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
end
respond_with(#user)
end
You didn't add the "role" attributes to the attr_accessible list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.
Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible is to protect your application from that.
You can still modify your user.role attribute on its own like below, but not with all attributes together.
#user.role = DEFAULT_ROLE
Why the hell would you use the attr_accessor?
Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.
For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field.
You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.
To be able to make use of this info you need to store it temporarily somewhere.
What more easy than recover it in a user.peekaboo attribute ?
So you add this field to your model :
class User < ActiveRecord::Base
attr_accessible :firstname, :lastname
attr_accessor :peekaboo
end
So you will be able to make an educated use of the user.peekaboo attribute somewhere in your controller to send an e-mail or do whatever you want.
ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save because she don't see any column matching this name in her model.
attr_accessor is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to
class MyModel
def my_variable
#my_variable
end
def my_variable=(value)
#my_variable = value
end
end
attr_accessible is a Rails method that determines what variables can be set in a mass assignment.
When you submit a form, and you have something like MyModel.new params[:my_model] then you want to have a little bit more control, so that people can't submit things that you don't want them to.
You might do attr_accessible :email so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.
That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.
So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.
attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.
Let's consider the following example
class Address
attr_reader :street
attr_writer :street
def initialize
#street = ""
end
end
Here we have used attr_reader (readable attribute) and attr_writer (writable attribute) for accessing purpose. But we can achieve the same functionality using attr_accessor. In short, attr_accessor provides access to both getter and setter methods.
So modified code is as below
class Address
attr_accessor :street
def initialize
#street = ""
end
end
attr_accessible allows you to list all the columns you want to allow Mass Assignment. The opposite of this is attr_protected which means this field I do NOT want anyone to be allowed to Mass Assign to. More than likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.
In two words:
attr_accessor is getter, setter method.
whereas attr_accessible is to say that particular attribute is accessible or not. that's it.
I wish to add we should use Strong parameter instead of attr_accessible to protect from mass asignment.
Cheers!
A quick & concise difference overview :
attr_accessor is an easy way to create read and write accessors in
your class. It is used when you do not have a column in your database,
but still want to show a field in your forms. This field is a
“virtual attribute” in a Rails model.
virtual attribute – an attribute not corresponding to a column in the database.
attr_accessible is used to identify attributes that are accessible
by your controller methods makes a property available for
mass-assignment.. It will only allow access to the attributes that you
specify, denying the rest.

Resources