Ruby on Rails Active Storage validation - ruby-on-rails

Is it possible to easily disable model validation only when attaching files? We have lots of data from our previous system that won't pass new validation rules and we can't attach any files to those. I know we could make another set of validation rules based on creation date (to allow older not not so good data) but we have dozens of different models so it wouldn't make sense to duplicate everything and up keeping the code would become very messy. And when normally updating some old data we still would want to use the new validation rules anyway.
Normally I can skip validations using .save(validate: false) but that approach doesn't seem to work when attaching files. We are using Ruby on Rails 6.

Related

What is reform's rationale for validation not being in models?

The reform gem advocates not having validations within models. Instead, it advocates them being in the form.
Validations From Models
...
Sometimes when you still keep validations in your models (which you
shouldn't) copying them to a form might not feel right. In that case,
you can let Reform automatically copy them.
...
Be warned that we do not encourage copying validations. You should
rather move validation code into forms and not work on your model
directly anymore.
What rationale does the reform gem project, or its authors, give for not having validation in models?
I would split validations into two different categories:
Data Integrity
Business Logic
Data integrity means the model can't be used without meeting certain criteria. You need to ensure the model will never be considered valid in this state.
Most of the time however this concerns things such as unicity which are persistence related. So these constraints would better be enforced at the database level rather than in the model.
Business Logic on the other hand is directly related to the functional needs of the application.
Let's take an example: When a user signs up I only want him to fill his e-mail but when he edits his profile I want to make sure he also fills in his first name and last name.
Considering validations belong to the model, you need to start cluttering it with conditional validations. Here you would check before validating if the model was persisted already or not and this would do the trick. But add more forms with different requirements and this quickly becomes an hell to manage.
That is because the validation logic depends on the context of the application (the form being filled by the user, the API endpoint being called ...). You want to validate that the parameters required by this application context are valid, not the model state.
Things become a lot more easy and maintainable if you set-up different sets of validation for each context. This leads to a bit more code to write but a lot cleaner and maintainable logic.

What are the steps for modifying an existing rails application

I am new to ruby on rails and I am working on a web application written by ruby on rails. It has more than 10 models and I need to add some new attributes to some of the models as well as new methods and views. I also will need to remove or enhance some of the functionality. I know that I would need to generate new migrations and from there add/remove new columns. Then in controllers, add/modify methods, and update the views.
I wanted to know what would be the best steps (and in which order) for doing the above tasks. Also, do I need to change other files in folders like test or any other folder? What things should I consider to minimize the troubles later?
Thanks in Advance.
Since you are new to rails, the first thing you should do is to read through the getting started guide. This will help you understand the fundamentals of the rails framework and the application you inherited. After that, there are several other guides worth reading (from the same site) that may be directly applicable to the work you are doing.
Another incredibly helpful resource is railscasts. Some of these are outdated, but they are still a great starting place and can help introduce you to both new, powerful gems and rails techniques to get the work done faster and better.
As to your specific question, rails is built on an MVC architecture (meaning Model Views Controllers). It is in your best interest to try and follow this practice whenever possible. Reading up on this will clarify some of your questions as well.
When you run a migration, you will be modifying your database. The changes are viewable in the database schema (which should never be modified by hand, always modify it through migrations). This will add attributes to your models whose table you modified. In the controllers, you will add logic to deal with all of these things and the views will present the data to your users (or allow users to enter data). Asking which order is best is probably rather opinion based, but I would say you should modify the tables (run needed migrations) first. This way you can then generate the logic to deal with the new attributes. I would then create the controller logic and finally the views.
You also ask what other files need to be changed. This is heavily dependent on your system. At a base level, you should definitely be writing tests to support the logic you are generating (and many developers will advocate that you should do this before you write the other logic, a process called Test Driven Development).
TL;DR: Read the guides, work through a basic tutorial, and watch some Railscasts. This should get you up to speed on the process and best practices that go along with rails development.

Create fake data to use as tutorial

I want to create fake usage of my app, as a tutorial.
In order to do so, I need to create fake data (with the same structure and association in real data) to send to my templates, so it renders the same view when my users will have when using the app.
But unfortunately, I didn't find an easy way to do that, except hard coding the examples (fake usage) as a separate view, that looks like the generated view with true data. But this is not useful when you have to change the template, one day or another.
And, mixing true data with fake ones in the database (and then retrieving only fake data when needed) doesn't seem to be a good idea.
Do you have an idea or a gem to suggest?
One option to consider is to use a factory gem (such as factory_girl) or similar (I personally like machinist) and then create some form of script that initializes objects in the test environment.
This may not be the intended or ideal use for a test environment, but you'd be able to utilize your app in a non-production environment with fake data, and allows you to keep data separate from real and/or development data.
The only "gotcha" I can think of is that you'll want to ensure that any automatic testing gem (such as rspec) drops the test database before your tests run. If you don't, you could see errors in your tests due to data already existing in the database.

How do I create a Validation Error Log

I have a rails 3 application that involves a lot of importing of CSV files from a third party into various rails models. I have developed some scripts to perform most of the heavy lifting and today I added a lot of validation to the models to make sure valid data is going into the models/tables.
I'd also like to do some logging of validation errors so I can stay on top of all of the data processing and catch and correct validation errors quickly. To that end, I have taken the following steps:
I created a ValidationError model to store validation errors.
I initially create an instance using new.
Once the object is built, I use valid? method and an if conditional to determine if the object it valid. If the the object is valid, I simply save it. If the object isn't valid I create a validation error record.
I use the errors method to populate my ValidationsError instance.
Then I create the ValidationError.create(validation_hash[])
I'll display the validationError model in my ActiveAdmin dashboard and send out an email when validation entries are created.
Question(s): Is my proposed approach to capturing validation error reasonable. Are there approaches that have been used by others that may be better/preferable to what I propose. Is anyone aware of any gems or built-in functionality that would accomplish what I'm trying to do.
Have a look at validation_rage gem. you might be able to use that gem to achieve what you want.
have also a look at this :)
Importing CSV file into multiple models at one time
and rail_admin_import gem, maybe you can expand with above staging table approach.

Helpers in rails

I'm just starting out in Rails and there's a lot I still need to learn so I'm likely to be on Stackoverflow more often than normal asking beginner Rails / Ruby questions.
I'm just trying to figure out how Helpers work in Rails. From what I've seen so far, Helpers are intended to be used with Views and not so much with your Controllers.
However I would like to make a simple function that will validate the user input given in params (check if certain params are defined and optionally check if their value is valid).
Can anyone explain to me what would be the best way of implementing this? (Keeping in mind that I will want to use this in many different controllers so it should be globally available.)
I also noticed that by default Rails does not generate a lib folder in the main application folder. Are developers to place their libs outside the app folder in the main folder, or does Rails use libraries differently?
With regards to your validation issue, it depends on what you are validating.
If the data makes up objects from your problem domain, also known as models, then you should use the built in validators from ActiveModel. This is probably what you should do, but its hard to say without knowing the exact problem. See the Rails Guides on Validations. You can tell if this is the case by asking yourself if the data that needs validation will be stored after you get it. If so, its most definitely a model. An example of this kind of data would be the title and text fields of a blog post being sent to Rails from a browser form.
If the data is something tertiary to your models, or specific to presentation, then you should be fine using helpers. You noticed that helpers are used mostly in the views, and although this is true, theres nothing stopping you from using them in the controllers, you just have to declare that you will use them using the ActiveController#helper method. Inside the ApplicationController class, a lot of devs will put helper :all to just include all the helpers in all the controllers. Once the code has been required once, it doesn't really incur that big a performance hit.
Do note that almost all incoming data can be modeled using a model. A big school of thought in the Rails world subscribes to the Fat Model idea. People say that putting as much code as possible in the model and as little in the controller as possible separates concerns properly and leads to more maintainable code. This suggests that even if you don't think the incoming data is modelable (in the sense that you can create a model to represent it), you should try to make it a model and encapsulate the logic around validating it. However, you may find that making a helper function is faster, and either will work.
Your notion of validating user input is a good one. I get the feeling that as you are new to Rails you are used to doing these things yourself, but that doesn't quite apply here. In the Rails world, a lot of the common stuff like validations is handled by the framework. You don't have to check for presence in the params array, instead you call validates_presence_of on the model and let Rails spit the error out to the user. It makes things easier in the long run if you let the framework do what it is designed to.
With regards to your question about the lib folder, it doesn't really matter. You can put miscellaneous support files and libraries in the lib folder in the root directory and they will be available for use in your application (the files in the app folder). You can also choose to abstract your code into a plugin or a gem and include it that way, which a lot of people opt to do. My suggestion for this would be to read up on the notion of gems and plugins before diving in.
Want you want is probably a custom validator (in Rails3):
http://railscasts.com/episodes/211-validations-in-rails-3
You can either add libs in a lib folder you create, or add them to config/initializers in a file you add. Files in the initializers directory are automatically loaded by Rails.

Resources