#ActiveRecord columns
Explore tagged Tumblr posts
Text
Integrating Databases with Ruby on Rails: Best Practices
In the realm of web development, Ruby on Rails (RoR) stands out as a powerful and efficient framework for building robust and scalable web applications. One of the core components of any web application is its database, and integrating databases with Ruby on Rails requires careful consideration and adherence to best practices. In this article, we will explore the importance of integrating databases with Ruby on Rails effectively and discuss some best practices to ensure optimal performance and maintainability. Additionally, we'll highlight the role of a reputable ruby on rails development company usa, in implementing these best practices.
Ruby on Rails simplifies the process of database integration by providing a set of conventions and tools that streamline common tasks such as database configuration, migrations, and querying. However, effective database integration goes beyond simply setting up a connection and defining models; it involves designing a database schema that aligns with the application's requirements, optimizing database performance, and ensuring data consistency and integrity.
One of the first steps in integrating databases with Ruby on Rails is selecting an appropriate database management system (DBMS) that meets the needs of the application. Ruby on Rails supports a variety of DBMS options, including MySQL, PostgreSQL, SQLite, and others. Each DBMS has its strengths and weaknesses in terms of performance, scalability, and features, so it's essential to carefully evaluate the requirements of the application and choose the right option accordingly.
Once a DBMS is selected, the next step is designing the database schema. This involves defining the structure of the database, including tables, columns, relationships, and constraints. In Ruby on Rails, database schema design is typically done using ActiveRecord migrations, which allow developers to define database changes in a version-controlled and reversible manner. When designing the database schema, it's crucial to follow established database design principles such as normalization, which helps minimize redundancy and ensure data integrity.
Another best practice in integrating databases with Ruby on Rails is optimizing database queries for performance. This involves writing efficient SQL queries and leveraging ActiveRecord's query interface to minimize database load and response times. Techniques such as indexing, eager loading, and caching can also help improve query performance and scalability. Additionally, developers should be mindful of potential performance bottlenecks such as N+1 query problems and strive to address them proactively.
Data consistency and integrity are paramount in any web application, and Ruby on Rails provides built-in mechanisms to ensure these principles are upheld. ActiveRecord validations allow developers to define rules for data integrity at the model level, preventing invalid or inconsistent data from being saved to the database. Transactions provide a way to group database operations into atomic units, ensuring that either all operations succeed or none do, thereby maintaining data consistency in the event of failures or errors.
Furthermore, effective database integration with Ruby on Rails involves implementing robust backup and recovery strategies to safeguard against data loss and corruption. Regular database backups, offsite storage, and disaster recovery plans are essential components of any backup strategy. Additionally, monitoring tools and alerts can help identify and address potential issues such as database downtime or performance degradation proactively.
While Ruby on Rails provides powerful tools and conventions for integrating databases, partnering with a reputable ruby on rails web development company usa can further enhance the process. A skilled and experienced development team can provide valuable insights and expertise in database design, optimization, and maintenance, ensuring that the database integration aligns with the application's goals and requirements. By leveraging the services of a trusted Ruby on Rails web development company in the USA, businesses can achieve optimal performance, scalability, and reliability in their web applications.
In conclusion,
integrating databases with Ruby on Rails is a critical aspect of web application development that requires careful planning, design, and implementation. By following best practices such as selecting the right DBMS, designing an efficient database schema, optimizing queries for performance, and ensuring data consistency and integrity, developers can build robust and scalable web applications that meet the needs of their users. Partnering with a reputable ruby on rails website development company usa can further enhance the database integration process, ensuring that the application's database meets the highest standards of quality and reliability.
#ruby on rails development company usa#ruby on rails web development company usa#ruby on rails website development company usa
0 notes
Text
January 16, 2024
New gem release: unreliable 0.10
I released a new version of a gem!
unreliable is a gem I wrote that makes your test suite and your app more robust against undefined database behevior.
During the running of your test suite, it adds randomness to the order of all your ActiveRecord relations. If their existing order is well-defined, that won't change a thing.
But if you have any relations where ordering actually matters, and you don't fully specify that order, the gem may surface some of those bugs.
SQL order can be undefined
Many people don't know that if a query has an ORDER BY clause that's ambiguous, the database can return results in any order. That's in the spec!
Because most databases, most of the time, return data in primary key order, we as programmers get used to that and maybe sometimes rely on it.
"unreliable" forces you not to rely on it.
Bugfixes and tests
Version 0.10 has several bugfixes related to Postgres. And it's got a large test suite that should give some confidence it's doing the right thing.
(It does exactly nothing outside of a Rails test environment anyway, so have no fear, it can't cause problems in your actual app.)
Give it a try!
Arel 8, subqueries, and update
Okay, this is just a footnote. Here's something that came up while I was writing "unreliable"'s test suite.
I found an odd edge case bug in Arel 8, the library used by the ORM in ActiveRecord 5.0 and 5.1. And although Arel was a public API at that point, really nobody but Rails was using it, and 5.1 is long-since end-of-lifed, so none of this really matters.
Where ActiveRecord calls Arel's compile_update, the relation is unscoped, so it can't have an order or limit.
But if it did, then when visit_Arel_Nodes_UpdateStatement built the SQL, it would construct an IN subquery and pass it a primary key that's quoted.
The resulting query that the visitor would build would be:
UPDATE foo SET bar=1 WHERE 'id' IN (SELECT 'id' FROM foo WHERE foo.id=2)
See the bug? 'id' should have been "id", which would have referenced the column. But it's single-quoted, and in SQL, that's a string literal!
So every row matches and the whole table gets updated! Yikes!
The bug never triggers for MySQL because MySQL forbids same-table subqueries on UPDATEs, so Rails special-cases around this.
And as I said, this is all ancient history, and almost certainly affects no one. But I think this is technically an Arel 8 bug that has been lurking undiscovered since February 2017.
This behavior was fixed in Arel 9. That's why "unreliable", which forces an order on most relations internally, after ActiveRecord forces an unscoping, now requires ActiveRecord >= 5.2.
0 notes
Text
Building Dynamic Web Applications with Laravel Development Services
Laravel is a popular open-source PHP framework, known for web application development. This tool, which is based on the Model-View-Controller (MVC) architectural pattern, is a top choice for businesses because it provides an array of benefits. This is why Laravel development services are becoming more and more popular.
Why is Laravel Gaining Popularity?
Since its creation in 2011, Laravel has become a favorite PHP framework due to its simplicity, elegance, and power. Its user-friendly syntax gives developers joy while working, making web development not only manageable but truly pleasurable. A Laravel development company uses this tool to produce high-end web applications that cater to your business needs.
Why Opt for Laravel in Web Application Development?
Laravel's growing fame stems from its flexible and broad-ranging features. Packed with features that accelerate web development and boost the quality of the end product, Laravel is a top pick for developers. Here's why:
Modular and MVC Architecture: Laravel is founded on over 20 different libraries and is divided into separate modules. This structure helps developers create modular and responsive web applications. With MVC, there's a clear distinction between logic and presentation, leading to better documentation and many scalable options.
Security: In web application development, safety is key. Laravel safeguards its framework. It uses hashed and salted passwords, which implies passwords aren't saved as plain text in the database. Laravel also has a user-friendly way to escape user input to prevent user injection attacks.
Database Migration: Laravel stands out due to its database migration feature. It not only lets you alter the database structure but does it using PHP code instead of SQL. Laravel Schema Builder enables quick creation of database tables and the insertion of indices or columns.
The Perks of Laravel Development Services
These services can help create unique, efficient, and user-friendly web applications. With its rich features, Laravel simplifies the web development process.
Here's how Laravel development services can boost your web application:
Artisan Console: Laravel has a built-in tool for the command line known as Artisan. This tool lets developers interact with Laravel via a command line, helping them manage the Laravel project environment. It helps avoid tiresome and repetitive programming tasks.
Eloquent ORM: The Eloquent ORM in Laravel offers a neat, simple ActiveRecord implementation for database work. Each database table links to a "Model" that lets you interact with that table.
Task Scheduling: Earlier, developers had to make a Cron entry for each task they needed to schedule. Laravel's built-in task scheduler solves this issue, offering an expressive, easy-to-use interface to schedule tasks.
Choosing a Laravel Development Agency
Selecting the right agency is vital for your web application's success. An expert Laravel development agency can create and maintain top-quality web applications. Here are some tips:
Expertise and Experience: Explore the company's portfolio to gauge their experience. This gives insight into their working style, project types, and success rate.
Client Testimonials and Reviews: Client feedback is an effective way to judge an agency's efficiency. An agency with positive reviews is likely to deliver quality work.
Support and Maintenance: After-development support is essential for your web application to run smoothly. Ensure your chosen agency provides strong support and maintenance.
Pricing: While cost shouldn't override quality, it's essential to choose an agency that fits your budget.
The Laravel Development Process
The development process involves several stages, from initial consultation to final delivery and support. A standard Laravel development company follows these steps:
1. Requirement Gathering and Analysis: This stage involves understanding the client's needs and the purpose of the web application. This requires extensive consultation to analyze the business requirements, target audience, and desired features.
2. Design: Once the requirements are clear, the next step is to design the application, which includes wireframing, UI/UX design, and creating a design prototype.
3. Development: This is where the actual coding and integration occur. The developers set up the Laravel environment, build the application as per the design, integrate the functionalities, and ensure smooth operation.
4. Testing: After development, the application undergoes rigorous testing to identify and fix bugs or issues. It is tested for functionalities, performance, compatibility, and security.
5. Deployment and Support: After passing the testing phase, the application is ready for deployment. A reputable Laravel development agency will also offer post-deployment support and maintenance services. Hire dedicated laravel developers at affordable prices.
Bottom Line
Laravel, a comprehensive and sophisticated framework, caters to all web application needs. It offers a myriad of features, making it a top choice for web application development. Regardless of whether you're a startup or a well-established business, choosing Laravel development services can give you a significant edge in today's digital world.
#laravel#laraveldevelopment#laraveldeveloper#laraveldevelopmentcompany#laravelframework#webdesigner#websitedevelopment#webdeveloper#websitedevelopmentcompany#itcompany#knightcoders#shivtechnolabs
0 notes
Text
#CISA: #Vulnerability Summary for the Week of December 5, 2022
#CISA: #Vulnerability Summary for the Week of December 5, 2022
Vulnerability Summary for the Week of December 5, 2022 12/12/2022 09:49 AM EST Original release date: December 12, 2022 High Vulnerabilities Primary Vendor — Product Description Published CVSS Score Source & Patch Info activerecord_project — activerecord A possible escalation to RCE vulnerability exists when using YAML serialized columns in Active Record < 7.0.3.1, <6.1.6.1, <6.0.5.1 and…
View On WordPress
0 notes
Photo
At some point, Tumblr restored this Kirby image that it took down around the time of the 2018 NSFW ban without ever giving me the option to appeal its NSFW status... Love wins.
This is a simulation of what I think was going on with the database in 2018 that resulted in my Kirby blog getting scrubbed with a wire brush:
class FilterBadPostsAgain2Imagemagick < ActiveRecord::Migration
def change
add_column :posts, :DONOTSHOW_2018ohno_imagemagickfilterv2, :boolean, default: false
Posts.all.each { |post| post.update_attributes!(DONOTSHOW_2018ohno_imagemagickfilterv2: true) if FilterHellAgain.imagemagickfilterv2_says_its_bad(post) }
end
end
and at least 3 different people did stuff like that independently within a week, and there was also one that suspended blogs based on the number of times "report" was ever hit on the blog/account in question (I feel like this may be why badsutheories got flagged as "adult"), and another for whole accounts? And none of these flagging systems necessarily knew what the others had decided or how, and the column values were all treated differently by the frontend, and the code for "imagemagickfilterv2_says_its_bad()" probably changed mid-migration somehow.
From 星のカービィ まとめ3 by R'L (Pixiv)
#i wrote that migration on my phone after looking at rails docs for a couple minutes so please do not correct its structure#ive thought too much about database migraines today already#do not fix that code nightpool!
49 notes
·
View notes
Text
TablePrint to structure your data
If you invest the time earlier to create structure and process around communication, planning, and goal-setting, you can prevent missteps before they occur. The same thing happens with the data structure. And we have a solution on how to make your life easier! You can use TablePrint to structure...
#ActiveRecord#ActiveRecord columns#ActiveRecord objects#backend#csv#data structures#github#OOP#Open source#ruby#Ruby gem#separator#TablePrint#web development
0 notes
Text
Work Better With Rails Web Application by Improving Database Indexes
For a very good reason, since past few years, Rails has been a foremost choice for a Ruby on Rails developer or Ruby On Rails Development Company in any kind of Web Application development. For beginners, it gets very easy to learn due to its readable coding methodology and for high skilled ROR developers, its abstractions make easy to build any kind of features in an efficient manner.
There is an unfortunate side effect of such kind of abstract understandings that lead to an especial problem when it comes to databases and SQLs.
Initially, when a Rails app is developed, it is used to be very fast and briskly. But, let say, if products count or users count gets flocked in all together in the Web Application, then web requests gets affected, and the databases CPU usage gets increased to the limit crossed level of height.
What is the reason for such slowing down of Rails Web Application?
At the initial stage of any Web application, due to less traffic, it works very smoothly and fastly. Here comes, Database queries, which plays a very important role in any Web application performance. If these are not managed in a way to handle a huge amount of traffic, then it leads to slowing down of application time to time. Huge traffic causes issues by running N+1 queries and if there is any lack of proper database indexes then it acts like the main culprit to it.
A Database Index is exactly what it sounds like. If we think about indexes present at the end of the book, those are very helpful in quick search of data with the help of pointers present in it. Without an index in the database, the query run gets typical when it finds every row to collect data and perform functionality, that leads to much more consumption of time load. For getting rid of it, adding index greatly speed it up.
Basic example:
While querying the user table, that is a common routining in any application.
Users.where(:email => current_user.email)
Rails automatically add the index to the id field of a database table. Whereas in this query we are asking it to find data record from some another field, here is EMAIL. If we need such kind of records than adding index for that data is mandatory.
class AddEmailIndexToUsers < ActiveRecord::Migration def change add_index :users, :email, :unique => true end end
Column indexing can be understood like a key in a hash. For large tables, or the tables those are frequently loaded by checking the values in 1 or 2 columns, adding an index to such kinds can provide highly efficient performance without upgrading the queries again and again.
In any table where foreign key exists, it additionally should have an index. When we add belongs_to: photo, Rails does not update the database to index user.photo_id. In such way, by every direction of our model’s user and photo lookup becomes fast and easy.
def up add_index(:users, :username) add_index(:users, :photo_id) end
Unique Column Constraints:
Database indexes can also be added by adding uniqueness on the columns. It not only helps in performance improvement rather works like a Rails validator as well.
When not to use Indexes:
By now, we have started thinking to use indexes in each and every database of every Rails Web application Development out there.
Wrong Idea !!
Although indexing works faster with select queries, whereas insert and update work quite slower by maintaining the indexes. However there are only milliseconds changes while any insert queries, but with huge traffic seconds also matters a lot in the application.
Use them wisely:
Indexes on columns of the table will always help in increase of speed, side by side it uses more disk spaces that can be a disadvantage for the Ruby on Rails application Development Company.
1 note
·
View note
Text
Elixir ecto
#Elixir ecto update
#Elixir ecto password
#Elixir ecto password
Authentication credentials, like your AWS password or key.PII (Personally Identifiable Information) such as a user's name or email address, which post-GDPR should be on every company's mind.These are some great examples for data scrubbing that every company should think about: That is, you would typically use put_assoc when you want to connectĪ record to one or more records that already exist in the database.As with any third-party service it’s important to understand what data is being sent to Sentry, and where relevant ensure sensitive data either never reaches the Sentry servers, or at the very least it doesn’t get stored. The association "references", not the data.
#Elixir ecto update
The crucial distinction is that put_assoc is designed to update However, upon closer examination, it turns out to be almost Defining Associations: put_assocĪt first glance, put_assoc is in many ways similar to cast_assoc: it also works on a whole associationĪnd requires you to pre-load records to be updated. Limiting the impact of cast_assoc to a subset of associated records. Well when you use preload as a subset of records with Repo.preload(:comments, query). However, you are not restricted to preloading a complete association. An important thing to note here is thatĮcto will not preload data on its own, so to make use of cast_assoc, you need to remember to call preloadīeforehand. The row with the ID of 11 was left unchanged because it matches preloaded values. INSERT a comment with a body "Interesting" and assign it a new id.UPDATE the comment with the id of 12 and set body to "Thank you for the post".Params = % post |> cast (params, ) |> cast_assoc ( :comments )Įxecuting this changeset results in three calls to the database: In that case, your models would look something like this. To give a concrete example, let's assume we work with two models, Post and Comment, where multiple comments can You treat the relation column as a normal database field. In a situation where you have the target ID, Ecto lets Working with associations doesn't always have to be complex. For a more in-depth comparison between ActiveRecord and Ecto,Ĭheck out this excellent ActiveRecord vs. The result is a somewhat higher learning curve,īut also, significantly increased flexibility. Records together and perform other tasks that ORM would try to automate. Ecto relies on a developer to formatĪnd validate the data to conform with the database schema, craft queries that use indexes efficiently, associate the It provides an Elixir syntax for crafting SQL queries themselves. The core conceptual difference is that Ecto does not intend to abstract away the database operations, instead, The precision of hand-crafted SQL queries.Įcto essentially provides the same tradeoff but leans much closer to the side of hand-crafted SQL queries. In this sense, ORMs propose a tradeoff between the convenience of language-native syntax and To achieve that, ORMs often perform complex transformations behind-the-scenes, which sometimes leads to suboptimalĭatabase performance. Traditional ORMs take on the massively complicated task of "masking"ĭata-related operations, giving developers the illusion of working with language-native data containers. The goal of this post is to give a short but definitive answer to such questions in a few of the most common The technical terminology in Ecto's official documentation. Online communities, choosing the right one can often be challenging, especially if the user is not yet accustomed to Judging from the number of questions about cast_assoc, put_assoc and build_assoc on StackOverflow and other Ecto provides multipleįunctions for establishing and modifying associations between records, each tailored to the particular use-case. Data modeling in Ecto takes a bit of getting used to, especially for developers that have mostly beenįor many novice Ecto users, association-related operations become the first stumbling stone.
0 notes
Text
Phase 3 Ruby Final Project
Hello! I have made it to the end of phase 3 and have finished my project. Using Ruby as my backend and React as the frontend. Ruby has been fun to learn and I like how the syntax used in it is like reading exactly what a method or class is doing.
Starting off, I will describe my web app, what it is for, and what functions it has. I created a web app that is for beehive owners. I got this idea from my uncle who has owned his share of beehives. This app is for displaying all your beehives and information about them. You start off by coming to the home page that welcomes you to the app. There is a home tab, owner tab, and beehives tab for you to click and view more information. I discussed what the home tab displays already. The owner tab will bring you to a list of all the owners of beehives on this web app. Then you can click on the beehives tab to view all of the beehives that each owner has. Each beehive shows the queen bee’s name, the owner’s name, and the amount of likes that beehive has. Also, along with each beehive is a button for liking the post and deleting the post. At the bottom of it is a form for creating and adding you own beehive to the list. In order to add your own hive you must give your first and last name, the queen’s name, the type of bees, and the number of boxes the hive has. Once the submit button is clicked it is then added to the page. While on this page you will see that each name for the queen’s name section is clickable. Once clicked it will bring you to info about that specific beehive. It lists out everything that was filled out in the form and also the amount of likes it has. That is all the functionality of this web app that there is so far, and I believe there is a lot more I could to with this as well.
Now to discuss what this project was about, Ruby, and what I did with my Ruby code to get this working. I started off with creating two migrations, one for creating an owners table and one for a beehives table. The owner’s table has two columns, which simply is the owner’s first and last name. The beehive’s table has four columns the queen’s name, the type of bees, the number of boxes, and an owner’s ID, also known as a foreign key. The foreign key is just the id for the owner who owns that specific beehive. There was also a third migration I created later on to add a likes column to the beehives table.
I seeded these table’s with some default data so I had something to work with when viewing the web app. Did this using .create on both models a few times and filling each one with different data.
Which I did create a model for each table. A Beehive class and an Owner class that both inherit from ActiveRecord::Base. In the Beehive class I just put belongs_to :owner, which is just saying this beehive belongs to an owner. In the Owner class I put has_many :beehives, saying that an owner can have many beehives. This creating the connection between both of the tables. I also included inside of the Owner class an instance method called full_name which just combines both the owner’s first and last name into a string.
Moving on to the controllers, I created a beehives controller which inherits from the application controller. Within this controller is where all the get, post, update, and delete information gets transferred through to the API to become the new updated data. So that when it comes through the frontend, React, it will display current and accurate data. There are two methods for getting data to display using “get”, and the part of the URL in which it will be grabbing the data. One is for getting all of the data about each beehive, and also includes the information of the owner of each beehive. It includes the owner data because I used the includes method, but I also used the except method to exclude the owner id. The second “get” grabs data about a specific beehive and its owner if its id matches the URL’s id number. So which ever id number the URL has it will find the beehive whose id matches using params. We then have our post, and it is going to look for an existing owner and if there is none it will create one. Next, create a beehive and assign it an owner ID that is the just found or created owner’s id that was posted along with it. To finally be saved with the rest of the other beehives and their data. This then becomes data to be used along with all the beehives and keeps everything current and updated. Patch is up next where we find a specific beehive where, again, if the URL’s param’s ID matches the beehives ID then that is the beehive we are patching/updating. This patch is for adding likes to a beehive. If the like button is clicked, whichever beehive it was clicked on, it will add one like to it. All of these methods gets the .to_json at the end in order to turn the hash into a JSON string. Finally, the last method is a delete. This, as it sounds, will delete a beehive from the API. Just as the patch it will get a specific beehive, which is the one that the delete button was clicked on. That one is then deleted and no longer apart of the rest of the data.
Adding on, I created a owner controller that does, as well, inherit from the application controller. The only method it has is a get to get all of the owner’s info for displaying. That is currently only the owner’s name.
To conclude, learning Active Record was a little difficult and, Ruby in general, was a lot different than JavaScript and React. I like how they can be paired together to create web apps and sites. I look forward to learn more in order to create more detailed, larger, and high functioning apps. I can see how far I have come, and though excited, I am getting more sad as we are now on phase 4 of 5 already.
0 notes
Text
Approach for Oracle view unit testing with Rspec
A View in Oracle and in other database systems is simply the representation of a SQL statement (select query). It provides access to a subset of columns from one or more tables. In a typical rails migration, when you incorporate a view definition which represents data from multiple tables with multiple joins and multiple conditions, how will you ensure that the view is fetching the data that it is supposed to fetch? How will you test the view logic? And here, Unit Testing plays a very important role. I had tried this simple approach in the past that we can follow for unit testing the view definition with Rspec. (may be with minor modifications as per context) First, with rails convention, you will create the model class (which maps to the view name) extending ActiveRecord::Base. You will then set up the test data as you generally set for testing other model methods. (You can use factory_girl or simple model methods) The purpose is to unit test each and every column data of the view according to the joins and the conditions. It all depends on the view logic that you have written according to your business requirement. The view definition can include decode statements, group by/ order by clauses, oracle aggregator functions e.g. sum, max, etc., function calls from the view sql, if-else logic to name a few. With this, you have all the unit level requirement specs ready for your view which you can validate by running your Rspecs.
0 notes
Text
300+ TOP RUBY ON RAILS Objective Questions and Answers
RUBY ON RAILS Multiple Choice Questions :-
1. What is bundler? a) rails generate scaffold User name:string email:string b) self-contained bundles of gems. Useful for versioning. c) Edit Gemfile, then run ‘bundle install’ or just ‘bundle’. d) Ruby Version Manager. Install and manage multiple versions of Ruby. Ans: C 2. What is gemset? a) self-contained bundles of gems. Useful for versioning. b) self-contained packages of Ruby code c) Ruby Version Manager. Install and manage multiple versions of Ruby. d) rails generate scaffold User name:string email:string Ans: A 3. What is gem? a) rails generate scaffold User name:string email:string b) self-contained packages of Ruby code c) self-contained bundles of gems. Useful for versioning. d) Ruby Version Manager. Install and manage multiple versions of Ruby. Ans: B 4. what is scaffold command? a) rails generate scaffold User name:string email:string b) Ruby Version Manager. Install and manage multiple versions of Ruby. c) self-contained packages of Ruby code d) self-contained bundles of gems. Useful for versioning. Ans: A 5. What is rake? a) self-contained bundles of gems. Useful for versioning. b) bundle exec rake db:migrate. Using bundle exec ensures that the rake version in our Gemfile is used. c) rails generate scaffold User name:string email:string d) Ruby Version Manager. Install and manage multiple versions of Ruby. Ans: B 6. What is rvm? a) rails generate scaffold User name:string email:string b) Ruby Version Manager. Install and manage multiple versions of Ruby. c) self-contained bundles of gems. Useful for versioning. d) self-contained packages of Ruby code Ans: B 7.how do you create a migration that adds a “phone” field to the “tickets” table? a) unit, functional, and integration tests b) RAILS_ENV (RAILS_ENV=production) c) integration test d) rails generate migration AddPhoneToTickets phone:string Ans: D 8.Rails’ application framework is called ———-? a) ActionPack b) ActiveRecord c) a web page d) an object Ans: A 9.how do you run a migration? a) CamelCase b) ruby make c) an object d) rake db:migrate Ans: D 10.what does “show” refer to as the :action value? a) the method within the controller to call b) HTTP methods (post, get, put, delete) c) the data being presented by the web page d) their names begin with an underscore Ans: A
RUBY ON RAILS MCQs 11.how do you update? a) update_attributes (as in @ad.update_attributes(params)) b) unit, functional, and integration tests c) format (that period is a concatenation period) d) it is not associated with a model Ans: A 12.what comes after Embedded Ruby -> ruby code (file.rb) -> fild.html c) the method within the controller to call d) the data being presented by the web page Ans: B 21.what is the filter code that calls on the “check_logged_in” method for only the “edit” and “update” methods? a) the data being presented by the web page b) HTTP methods (post, get, put, delete) c) data from model objects AND the page template d) before_filter :check_logged_in, :only => Ans: D 22.representation of a resource is called ————-. a) CamelCase b) ruby make c) a web page d) ActionPack Ans: C 23.converts database records to objects is called ————-. a) for ad in @ads b) integration test c) Representational State Transfer d) an object-relational mapping library Ans: D 24.what checks if an input is numeric? a) integration test b) a responder object c) validate d) validates_numericality_of Ans: D 25.what is Rails’ object-relational mapping library? a) CamelCase b) ActiveRecord c) an object d) underscores Ans: B 26.where do you add the filter code? a) rails generate migration AddPhoneToTickets phone:string b) the data being presented by the web page c) data from model objects AND the page template d) right after the line introducing the class in the controller Ans: D 27.why is it good to redirect after inserting info into the database? a) unit, functional, and integration tests b) a script that alters the structure of the underlying database c) so that users can’t accidentally resubmit information by refreshing the page d) the data being presented by the web page Ans: C 28.which two steps to include test.xml data to the partial “map” (via the variable “data”)…? a) from general to specific (‘/ads/’ and then ‘/ads/:id’) b) include test.xml to root of “public” folder and , render (:partial=>’map’, :locals=>{:data=>’/test.xml’}) c) just replace the word “scaffold” with the word “model” d) login method (that checks a username and password) and , a filter (that calls the login method when needed) Ans: B 29.what environments does Rails have by default? a) development, test, production b) render :partial c) RAILS_ENV (RAILS_ENV=production) d) integration test Ans:A 30.how do you generate regular model code (not scaffolding)? a) just replace the word “scaffold” with the word “model” b) it is not associated with a model c) username == “admin” && password == “some_password” d) do |f| (where “f” can be anything) Ans: A 31.how should you order routes? a) just replace the word “scaffold” with the word “model” b) from general to specific (‘/ads/’ and then ‘/ads/:id’) c) rails generate migration AddPhoneToTickets phone:string d) do |f| (where “f” can be anything) Ans: B 32.what should you write in routes.rb to give meaning to http://mebay.com/ads/3? a) from general to specific (‘/ads/’ and then ‘/ads/:id’) b) map.connect ‘/ads/:id’, :controller=>’ads’, :action=>’show’ c) include test.xml to root of “public” folder and ,render (:partial=>’map’, :locals=>{:data=>’/test.xml’}) d) form_for(@object, :url=>{:action=>’create’}) Ans: B 33.to add login security, which two pieces of code do you need? a) 1.all important data is a resource2. every resource has a proper name (URL) b) .:format (that period is a concatenation period) c) the method within the controller to call d) 1. login method (that checks a username and password) and 2. a filter (that calls the login method when needed) Ans: D 34.how do partials look compared to regular erb files? a) underscores b) it runs its validators c) it is not associated with a model d) their names begin with an underscore Ans: D 35.how does “rake” differ from “ruby”? a) right after the line introducing the class in the controller b) a script that alters the structure of the underlying database c) it can do more complex things like modifying the database structure and running tests d) expression is ruby code that prints out a value in html Ans: C 36.why should partials generally use local variables? a) because they make the partial less dependent on other code b) the data being presented by the web page c) their names begin with an underscore d) the request parameters table Ans: A 37.do models have singular or plural names? a) controller b) CamelCase c) flight_id d) singular Ans: D 38.how does rake tell which migrations have been run and which have not? a) rails generate migration AddPhoneToTickets phone:string b) rails records the latest timestamp of all the migrations it runs (and runs only the latest ones) c) because they make the partial less dependent on other code d) it can do more complex things like modifying the database structure and running tests Ans: B 39.how does Rails choose to correct format to generate? a) in the controller: respond_to do |format| … end b) it is not associated with a model c) redirect_to ” … ” d) the data being presented by the web page Ans: A 40.how do you express error messages in a form (do |f|)? a) ruby make b) f.error_messages c) for ad in @ads d) underscores Ans: B 41.what are the three “magic columns” a) id, created_at, updated_at b) render :partial:id c) integration test d) rake db:migrate:id:delete Ans: A 42.what tag starts a form? a) integration test b) c) d) Ans: C 43.what is params? a) have the same URL of a table b) the word “private” c) a responder object d) the request parameters table Ans: D 44.what comes after “def check_logged_in” line for site “ads”? a) in the controller: respond_to do |format| … end b) errors.add_to_base(“there was an error”) c) .:format (that period is a concatenation period) d) authenticate_or_request_with_http_basic(“Ads”) do |username, password| Ans: D 45.what is naming convention for classes? a) ActionPack b) CamelCase c) ruby make d) a web page Ans: B 46.to create scafolding for “thing” data, run… a) because they make the partial less dependent on other code b) expression is ruby code that prints out a value in html c) just replace the word “scaffold” with the word “model” d) rails generate scaffold thing : : Ans: D 47.what variable changes the environment? a) RAILS_ENV (RAILS_ENV=production) b) development, test, production c) render :partial d) validates_numericality_of Ans: A 48.what is naming convention for file names ? a) ActiveRecord b) underscores c) an object d) validate Ans: B 49.why do you only need to call “render” in the controller sometimes and not always? a) .:format (that period is a concatenation period) b) redirect_to ” … ” c) errors.add_to_base(“there was an error”) d) if you’re happy with the default template, you can omit “render” Ans: D 50.a RESTful application uses … to define an interaction with the data. a) a responder object b) it is not associated with a model c) HTTP methods (post, get, put, delete) d) the request parameters table Ans: C RUBY ON RAILS Objective type Questions with Answers 51.what generates web pages from page templates? a) underscores b) Embedded Ruby (ERb) c) a web page d) render :partial Ans: B 52.where do you edit routs? a) :controller b) underscores c) ActiveRecord d) config/routes.rb Ans: D 53.if looping through “f” object, how do you make a text field “name”? a) b) … have the same URL c) d) Ans: D 54.what does a model object do before it saves or updates data? a) underscores b) it runs its validators c) validate d) rake db:migrate Ans: B 55.what does “rake” mean? a) #{1+1} b) singular c) ruby make d) flight_id Ans: C 56.how do you start a loop that reads through the array object “@ads”? a) a web page b) ruby make c) for ad in @ads d) ActionPack Ans: C 57.what scripts does the model-generator command create? a) their names begin with an underscore b) the model class (app/models/something.rb) and the data migration (db/migrate/…_create_something.rb) c) model names are singular, controller (and table) names are plural d) rails generate migration AddPhoneToTickets phone:string Ans: B 58.what does Embedded Ruby (ERb) process as inputs? a) data from model objects AND the page template b) HTTP methods (post, get, put, delete) c) it is not associated with a model d) their names begin with an underscore Ans: A 59.what kind of test do you create yourself? a) an object b) ActionPack c) rake db:migrate d) integration test Ans: D 60.what is “format” in “repond_to do |format|”? a) underscores b) an object c) a responder object d) integration test Ans: C 61.what does REST stand for? a) runs State test b) the request State Transfer c) Representational State Transfer d) runs State Transfer Ans: C 62.what parameters are in ? a) data from model objects AND the page template b) form_for(@object, :url=>{:action=>’create’}) c) .:format (that period is a concatenation period) d) do |f| (where “f” can be anything) Ans: B 63.how do you add an error (called “there was an error”) in the validate method? a) redirect_to ” … ” b) errors.add_to_base(“there was an error”) c) the word “private” d) their names begin with an underscore Ans: B 64.how do you call a partial? a) a web page b) underscores c) singular d) render :partial Ans: D 65.how do you run the latest migrations? a) ruby make b) a web page c) rake db:migrate d) CamelCase Ans: C 66.what’s special about a search form? a) for ad in @ads b) it is not associated with a model c) Representational State Transfer d) it runs its validators Ans: B 67.what expression do all layouts have? a) b) c) integration test d) Ans: A 68.if the table Seats is associated with the table Flights, how should you name the table column in Seats to indicate its flight? a) an object b) flight_id c) ruby make d) #{1+1} Ans: B 69.how would you insert “1 + 1” into a string? a) CamelCase b) #{1+1} c) singular d) validate Ans: B 70.what is the second uri indicate? a) an object b) ActionPack c) CamelCase d) :controller Ans: D 71.what precedes the “check_logged_in” method in a class? a) the request parameters table b) the word “private” c) d) redirect_to ” … ” Ans: B 72.what method name indicates to rails that it should validate before saving/updating? a) validate b) ActionPack c) flight_id d) ruby make Ans: A 73.how do you ask for all records of the Ads table? a) singular b) @ads = Ad.find(:all) c) validate d) rake db:migrate Ans: B 74.when data is retrieved from the database, what does Rails turn it into? a) a responder object b) validate c) flight_id d) an object Ans: D 75.what are the main principles of REST? a) 1. all important data is a resource, 2. every resource has a proper name (URL), 3. you can perform a standard set of operations on resources (usually CRUD), 4. client and server talk statelessly b) model names are singular, controller (and table) names are plural c) a script that alters the structure of the underlying database d) no. arrays just keep references to objects stored in memory. Ans: A 76.When is it best to use an array rather than a hash? a) An array uses indices and a hash uses “keys” b) puts (pronounced “put-ess”) c) Red refers to writing a failing test d) When the order matters, use an array. Ans: D 77.Describe the TDD cycle. a) An array uses indices and a hash uses “keys” b) It’s a test that simulates a browser accessing our application. c) Red, Green, Refactor,Red refers to writing a failing test,Green refers to writing a passing test Once we have a passing test we are free to refactor the code. d) This maps requests for the URL /pages/home to the home action in the Pages controller. Ans: C 78.How does a local variable differ from an instance variable when empty? a) This is not a standard rails directory, but a directory installed by RSpec in which all test files are kept. b) The @ indicates that this is an “instance variable”. An instance variable defined in the action (or function) of a controller is automatically available in the view of that same name. c) It’s a test that simulates a browser accessing our application. d) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined Ans: D 79.What is a .erb file? a) The “erb” stands for “Embedded RuBy”. .erb files look like about.html.erb and live in the “views” directory.They are just html files with embedded ruby in them. b) The @ indicates that this is an “instance variable”. An instance variable defined in the action (or function) of a controller is automatically available in the view of that same name. c) puts (pronounced “put-ess”) d) It’s a test that simulates a browser accessing our application. Ans: A 80.What’s the best way to describe an object in Ruby? a) An array uses indices and a hash uses “keys” b) It’s easier to describe what objects do, which is respond to messages. An object like a string, for example, can respond to the message length, which returns the number of characters in the string c) This maps requests for the URL /pages/home to the home action in the Pages controller. d) It’s a test that simulates a browser accessing our application. Ans: B 81.What is a Class? a) An array uses indices and a hash uses “keys” b) Classes are simply a convenient way to organize functions (also called methods). In pages_controller.rb, PagesController is a Class which holds a “home” action. c) A controller is a container for a group of (possibly dynamic) web pages. d) This maps requests for the URL /pages/home to the home action in the Pages controller. Ans: B 82.What kind of object is “@title” and what is special about it in Rails? a) It’s a test that simulates a browser accessing our application. b) The “erb” stands for “Embedded RuBy”. .erb files look like about.html.erb and live in the “views” directory.They are just html files with embedded ruby in them. c) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined d) The @ indicates that this is an “instance variable”. An instance variable defined in the action (or function) of a controller is automatically available in the view of that same name. Ans: D 83.What does the routes.rb file do with “get pages/home”? a) When a request is made for, say, /pages/home, the Pages controller executes the code in the “home” action and then automatically renders the view corresponding to the action — in this case, home.html.erb. b) This maps requests for the URL /pages/home to the home action in the Pages controller. c) When the order matters, use an array. d) It’s a test that simulates a browser accessing our application. Ans: B 84.Describe a “symbol” in Rails? a) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined b) Symbols look kind of like strings, but prefixed with a colon instead of surrounded by quotes. For example, :name is a symbol. You can think of symbols as basically strings without all the extra baggage c) An array uses indices and a hash uses “keys” d) This is not a standard rails directory, but a directory installed by RSpec in which all test files are kept. Ans: B 85.What is the status code for “success” when throwing a GET? a) 300 b) 200 c) 400 d) 150 Ans: B 86.What is the command to print to the screen? a) When the order matters, use an array. b) An array uses indices and a hash uses “keys” c) It’s a test that simulates a browser accessing our application. d) puts (pronounced “put-ess”) Ans: D 87.What is the main benefit that a Class gets by inheritance from ApplicationController? a) An array uses indices and a hash uses “keys” b) When a request is made for, say, /pages/home, the Pages controller executes the code in the “home” action and then automatically renders the view corresponding to the action — in this case, home.html.erb. c) This maps requests for the URL /pages/home to the home action in the Pages controller. d) When the order matters, use an array. Ans: B 88.Name two ways to indicate a “block” in Rails a) This maps requests for the URL /pages/home to the home action in the Pages controller. b) The request hits the rails router which dispatches to the proper controller action. In this case, it goes to the index action in the Users controller. c) Curly braces or do..end. It’s best to use curly braces for short one-line blocks and the do..end for mult-iline blocks. d) When the order matters, use an array. Ans: C 89.What is an integration test? a) It’s a test that simulates a browser accessing our application. b) When the order matters, use an array. c) puts (pronounced “put-ess”) d) An array uses indices and a hash uses “keys” Ans: A 90.What is the most special aspect of nil? a) This maps requests for the URL /pages/home to the home action in the Pages controller. b) A controller is a container for a group of (possibly dynamic) web pages. c) When the order matters, use an array. d) Other than the object “false” itself, nil is the only object that defaults to false. Ans: D 91.What is the /spec directory in rails? a) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined b) Symbols look kind of like strings, but prefixed with a colon instead of surrounded by quotes. For example, :name is a symbol. You can think of symbols as basically strings without all the extra baggage c) This is not a standard rails directory, but a directory installed by RSpec in which all test files are kept. d) This maps requests for the URL /pages/home to the home action in the Pages controller. Ans: C 92.What’s the difference between a hash and an array? a) An array uses indices and a hash uses “keys” b) When the order matters, use an array. c) It’s a test that simulates a browser accessing our application. d) puts (pronounced “put-ess”) Ans: A 93.What is a controller? a) A controller is a container for a group of (possibly dynamic) web pages. b) An array uses indices and a hash uses “keys” c) It’s a test that simulates a browser accessing our application. d) When the order matters, use an array. Ans: A 94.how do you define a “status” parameter (within a “tweet” parameter)? a) code = tweet,url = /tweets/1 b) @tweet = Tweet.create(:status => params) c) params = {:tweet => {:status => “I’m dead” }} d) @tweet = Tweet.create(:status => params) Ans: D 95.how do you check the logged in user’s id? a) :status b) session c) t.errors d) the attribute Ans: B 96.let’s say you have a method��� def get_tweet @tweet = Tweet.find(params) end how do you tie an action to that that only kicks in for the edit, update, and destroy methods? a) index, show, new, edit, create, update, destroy b) code = tweet, :method => :delete url = /tweets/1 c) before_filter :get_tweet, :only => d) @tweet = Tweet.create(:status => params) Ans: C 97.How to includes all javascript? a) b) c) d) Ans: B 98.what do you use to send messages to the user? a) t.errors b) :status c) a flash d) @tweet Ans: C 99.How includes all stylesheet files? a) b) c) d) Ans: D 100.How do you make sure your forms don’t get hacked? a) b) c) d) tweets_path Ans: B RUBY ON RAILS Questions and Answers Pdf Download Read the full article
0 notes
Link
There are many ActiveRecord changes in Rails 6. We will look into some of them which are as below.#pick, #create_or_find_by/! Negative scopes for all enum values and Configurable implicit order column.
0 notes
Text
migrations - create new columns
rails g migration AddImageAndCapacityToEvents image_file:string capacity:integer
Adds 2 columns to the events table
class AddImageAndCapacityToEvents < ActiveRecord::Migration[5.2]
def change
add_column :events, :image_file, :string
add_column :events, :capacity, :integer
end
end
Add the default values manually
add_column :events, :image_file, :string, default: ""
add_column :events, :capacity, :integer, default: 1
save then rails db:migrate
0 notes
Text
Replace a database column with ActiveRecord with zero downtime
There are times with your web application where you want to switch a database column. Perhaps you discovered that the data sits better on a different table or perhaps the data stored in that single column needs to be split across two. This is a problem teams I’ve been on at GDS seem to face every now and again and I thought I’d take the opportunity to document the process I recommend to developers.
Often developers approach this task by trying to complete this task with their changes all wrapped into a single deployment, which is reasonable if you’re prepared to take your application down for maintenance. However if you want to keep the application available and avoid serving errors you’ll need to follow a multi-step process with a number of deploys with distinct migrations. Depending on the risks involved in switching your column you may also want to keep the door open to rolling back the application to using the old column.
The basic steps to this are: create the new column(s) in the db and set the application to fill this whenever it writes or updates the old value; create a task to loop through the old data to backfill the new column; switch the application to use the new column; then drop the old one. What follows are the considerations to make at each one of these steps and examples of how this is done using ActiveRecord with Ruby on Rails.
Step 1: Introduce new column and populate it when new records are entered
The first step is to add the new column to the database. This can be done by a standard Rails migration. At GDS we’ll regularly consult braintree’s handy guide to safe operations for high volume PostgreSQL to determine our initial migration won’t block the DB. There’s also an interesting gem, strong migrations, that can warn you for PostgreSQL when you’re going to run a dangerous migration. There are likely similar resources for other popular database flavours.
The application should then be adjusted so that whenever a record is created or updated this new column is populated. This step is required before backfilling this new column with existing data, the reason for this is that during the process of backfilling new data may be written to the application and thus the backfill will end up missing data or having out of date data.
At the point of adding this new column there is also an opportunity to make amends to the column that is being migrated away from, such as dropping a non-null constraint.
Example
Given we’ve decided the field document_type needs moving from the Document model to the Edition:
class Document < ApplicationRecord has_many :editions # Document has a document_type value that is moving to editions end class Edition < ApplicationRecord belongs_to :document end
We can create the column with a migration:
class AddDocumentTypeToEdition < ActiveRecord::Migration[6.0] def change add_column :editions, :document_type, :string end end
We can populate records that are saved with an ActiveRecord callback (to avoid changing application business logic) if our change is simple:
class Edition < ApplicationRecord belongs_to :document before_save { self.document_type = document.document_type } end
If migrations are run automatically as part of a deploy (before the application code switches over) this whole step can be done in a single deploy, if not the migration will have to be deployed and run before the change to populate
Step 2: Backfill the new column
Now that any new writes to the table populate the column the next aim is to fill the column for all the existing records of the database. To do this some code is needed to iterate through all the records in the database and updating the record for each one.
You may choose to do this with another migration or a Rake task. Your choice here will depend on your attitude to what belongs in a Rails migration - a purist may only want to have commands that alter the database structure and nothing that alters data structure. Myself, I don’t mind them being as a migration because it keeps it’s a consistent place with the other database operations and doesn’t clutter parts of the app once they’re run.
Some things to consider with this task are: a backfill can take a long time and thus may fail in some way, it’s good if they can pick up where they failed if that happens; doing everything in a single transaction may cause performance problems once the transaction becomes huge; and using any application ActiveRecord classes carries risks if those classes have changed at the point a different user runs the migration.
Example
class BackfillDocumentTypeOnEdition < ActiveRecord::Migration[6.0] # We use this to run the migration outside a transaction, which allows resuming and reduces DB load disable_ddl_transaction! # create a private instance of an ActiveRecord object so that we don't need to use our application code class Edition < ApplicationRecord belongs_to :document end def up # by removing nil records we can resume a failed run of this and only update what was missed to_update = Edition.includes(:document).where(document_type: nil) total = to_update.count to_update.find_each.with_index do |edition, index| # for a long running migration/task it's useful to provide progress puts "Updated #{i}/#{total} edition document types" if (i % 1000).zero? edition.update!(document_type: edition.document.document_type) end puts "Updated #{total} edition document types" end def down # don't do anything, all these changes can be removed by rolling back the previous migration that added the column end end
This backfill will need to be deployed and run before we move onto the next step of starting to use the new column.
Step 3: Swith to using the new column
The new column should now be fully populated and the application can have it’s logic switched to make use of it. This is also an opportuntity to write any migrations that apply constraints (such as non-null) or defaults to the new column.
A key decision at this point is whether or not to provide a safety net to allow rolling back if the deploy has problems. Once the application stops populating the old column then rolling back is not possible, you’ll have to fix forward. In my experiences I’ve tended to not set-up the need for rollback and instead be cautious my deploy isn’t coupled with other changes but your circumstances may differ as may the impact a problem would have on your application/business.
If you are in a situation where you run staggered deploys (for example gradually deploy to a number of machines then others) your hand will be forced to need the rollback so that the application can work with both versions of the codebase.
With no rollback
If a rollback is not considered necessary then the next deploy of the application is focussed on the application making use of the new column. This would be represented by changing the application logic to use the new column that was introduced and no longer make references to the old column.
Without a rollback we can combine the deploy to change application logic with step 4 of deprecating the old column to reduce the number of deploys needed in this process.
With ability to rollback
To allow rolling back a deploy that switches the application to use the new column it is necessary to have a process which keeps the old column populated while the rest of the application switches to using the new column. To do this you’ll need to make all the necessary logic changes that favour the new column and then do a reversal of the process in step 1 to keep the old column populated.
Example
class Edition < ApplicationRecord belongs_to :document after_save do document.update!(document_type: document_type) if document.document_type != document_type end end
Step 4: Deprecate the old column
Once the new column is in use and you are satisified that the process is successful the work can begin to get rid of the old column. Any code that was added to populate the old column can be removed.
It’s common for a developer to proceed to add a migration to remove the column that is no longer needed, this however carries a risk of application errors which can be alleviated with an intermediatry step (which unfortunately requires another deployment). The type of error you may see if you remove the column are: "PG::UndefinedColumn: ERROR: documents.document_type does not exist", the reason you’d see these is because ActiveRecord caches the underlying columns when the application starts. It then uses this cache when an ActiveRecord object instance is loaded to select each column from the database.
This error can be avoided by using the ignored_columns method that was introduced to ActiveRecord in Rails 5. Once Rails has been deployed with the column ignored we are then safe to remove the column.
Example
class Document < ApplicationRecord has_many :editions self.ignored_columns = %w[document_type] end
Step 5: Remove old column then relax and celebrate
Finally, the last step is the simplest one. All that is needed is the actual removal of the old column. This can be done by a simple migration. We can then set out a sigh of relief that this process is complete.
Example
class RemoveDocumentTypeFromDocument < ActiveRecord::Migration[6.0] def change remove_column :documents, :document_type end end
Has this procress helped you or do you do something different? Let me know on Twitter.
0 notes
Text
rails: notes
$ bin/rails g migration AddNameToTable name:string $ bin/rails g migration RemoveNameFromTable name:string $ bin/rails g migration -h
To reset default, or null when changing a column, they must be specified explicitly. To drop the default, use change_column_default (change_column_default :table, :column, nil).
Rails 4: List of available datatypes ActiveRecord::ConnectionAdapters::SchemaStatements#add_column
puma apparently ignores RAILS_ENV, use -e switch.
logging
Unless config.logger is set rails falls back to log to log/#{Rails.env}.log. Additionally, bin/rails server sets up logging to stdout. In production environment, if RAILS_LOG_TO_STDOUT is set, rails sets up stdout log. To make it log to stdout in other environments, add config.logger = Logger.new(STDOUT) to config/environments/ENV.rb.
starting several servers
Rails expects server to have pid. Setting it to nil or empty string doesn't seem to work. So you've got to specify custom pidfile and custom port:
bin/rails s -P tmp/pids/server2.pid -p 9393
puma fails to restart after adding gems
Puma not restarting (or at least not loading new current) when notified with SIGUSR2
db tasks
db:migrate:reset = db:drop + db:create + db:migrate
If there's no database name in database.yml for current rails env, db:drop (or other tasks that create/drop database, or load schema) doesn't do anything..
But one may not specify database explicitly. For that one needs to createdb and bin/rails db:migrate.
db:purge = db:drop + db:create
lib/active_record/railties/databases.rake#L55 lib/active_record/tasks/database_tasks.rb#L220 lib/active_record/tasks/database_tasks.rb#L209 lib/active_record/tasks/postgresql_database_tasks.rb#L47-L48
When tests are run, rails checks if migrations are pending, and if they are, it tries to load the scheme:
test_helper.rb: require 'rails/test_help' rails/test_help.rb: ActiveRecord::Migration.maintain_test_schema! ActiveRecord::Core.maintain_test_schema config.active_record.maintain_test_schema = true ActiveRecord::Migration.maintain_test_schema!: load_schema_if_pending! ActiveRecord::Migration.load_schema_if_pending!: db:test:prepare db:test:prepare: db:test:load db:test:load: db:test:purge + db:test:load_schema
db:test:* tasks involving creating/dropping database, connect to database postgres. And use settings from test rails env as a base.
rake: trace
mina enables tracing, so it's best to have require: false for all mina* gems.
invoking rails commands
When no application exists yet (rails new ra3), application command is executed.
It check if the first argument is new.
It then starts to execute methods starting with set_default_accessors!.
To understand what's going on, you might need to consult the following files and manual pages:
railties/lib/rails/generators/rails/app/app_generator.rb railties/lib/rails/generators/app_base.rb railties/lib/rails/generators/base.rb Thor::Actions Thor::Shell::Basic
When application has already been created, it goes like this (bin/rails runner 'puts 123'):
Also, perform method is aliased as command name.
allow CORS requests
config/environments/development.rb:
# Allow CORS requests from webpack-dev-server config.middleware.insert_before 0, Rack::Cors do allow do origins ENV['FRONT_END'] resource '/api/*', methods: :any, headers: ['Content-Type'] end end
To enable debug mode, add {debug: true} parameter after Rack::Cors.
app server defaults
To run puma, bin/rails uses Rack::Server. But it passes to the latter its own options. So Rack::Server's defaults get ignored.
When running puma directly, its defaults can be found here.
autoload_paths
Rails::Engine < Railtie: initializer: set_autoload_paths: ActiveSupport::Dependencies.autoload_paths.unshift(_all_autoload_paths) Rails::Engine < Railtie: _all_autoload_paths: config.eager_load_paths Rails::Engine::Configuration < Rails::Railtie::Configuration: eager_load_paths: paths.eager_load Rails::Engine::Configuration < Rails::Railtie::Configuration: paths Rails::Paths::Root: eager_load: filter_by(&:eager_load?)
including modules
Issue that ActiveSupport::Concern solves:
module M1 def self.included(klass) klass.extend(ClassMethods) end def im1 puts 'im1' end module ClassMethods def cm1 puts 'cm1' end end end module M2 include M1 def self.included(klass) # klass.extend(M1::ClassMethods) klass.extend(ClassMethods) end def im2 puts 'im2' end module ClassMethods def cm2 puts 'cm2' end end end class A include M2 end A.new.im1 A::cm1 A.new.im2 A::cm2
require 'active_support/concern' module M3 extend ActiveSupport::Concern included do def im3 puts 'im3' end end class_methods do def cm3 puts 'cm3' end end end module M4 extend ActiveSupport::Concern include M3 included do def im4 puts 'im4' end end class_methods do def cm4 puts 'cm4' end end end class B include M4 end B.new.im3 B::cm3 B.new.im4 B::cm4
#en#tech#dev#rails#ruby#migration#generate#rails cheat sheet#rails notes#notes#cheat sheet#server#pid#several#several instances#several servers#port#instance#db#migrate#reset#drop#create#db reset#db migrate reset#db drop#db create#db migrate#rake#mina
0 notes
Text
SELECT, Beyond the Basics
I admit, I’m somewhat spoiled by ORM tools -- most notably ActiveRecord -- which hide database queries behind layers of objects and method chains.
This makes me lag behind somewhat with the assignments for my DB class, in which I have to write raw SQL.
In this post, I’m going to put together some info on PostgreSQL’s SELECT, going beyond the elementary stuff.
Set operations
UNION, INTERSECT, and EXCEPT share the same general form:
SELECT ... FROM ... (UNION | INTERSECT | EXCEPT) SELECT ... FROM ...
By default, the operations remove duplicate rows from the result set. The behavior can be changed by appending ALL:
UNION ALL does not discard duplicate rows, and therfore performs better.
With INTERSECT ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear min(m,n) times in the result set.
With EXCEPT ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear max(m-n,0) times in the result set.
Multiple clauses in the same SELECT statement are evaluated left to right. INTERSECT has higher precedence than UNION.
Ordering
ORDER BY sorts the result rows according to the specified expressions. Rows that are equal according to the leftmost expression are compared according to the next expression and so on. If they are equal according to all expressions, the order is implementation-dependent.
An expression can be a number, referring to the ordinal (left-to-right) position of the output column, e.g. SELECT city, temp FROM weather ORDER BY 2.
It is possible to specify columns that do not appear in the output list, e.g. SELECT city FROM weather ORDER BY temp.
A name that matches both an output column name and an input column name is interpreted as the output column name.
Ordering options apply only to the expression they follow: ORDER BY 1, 2 DESC is not the same as ORDER BY 1 DESC, 2 DESC.
An expression can be a CASE, for example:
SELECT * FROM people ORDER BY CASE gender WHEN 'female' THEN name ELSE last_name END DESC;
Aggregate Functions
The main ones are avg, count, max, min, sum. A usage example from the documentation is:
SELECT max(temp) FROM weather;
The first limitation to consider is that the WHERE clause is evaluated before aggregate functions are computed (it determines which rows will be included in the aggregate calculation). It means that something like SELECT city FROM weather WHERE temp = max(temp) does not work.
What we need is an independent computation, or a subquery:
SELECT city FROM weather WHERE temp = (SELECT max(temp) FROM weather);
Aggregate functions can be computed for groups of rows specified by GROUP BY:
SELECT city, MAX(temp) FROM weather GROUP BY city;
(Returns every city along with the maximum temperature registered in it.)
Unlike WHERE, a HAVING clause selects group rows after aggregates and groups are computed, making it useful for filtering results:
SELECT city, max(temp) FROM weather GROUP BY city HAVING max(temp) < 40;
When the output of a function depends on the order of inputs, an ORDER BY can be added after the last argument:
SELECT string_agg(city, ', ' ORDER BY date DESC) FROM weather;
PostgreSQL 9.4 added support for a FITLER (WHERE ...) clause that specifies which rows are fed to the aggregate function:
SELECT count(*) AS unfiltered, count(*) FILTER (WHERE i < 5) AS filtered FROM generate_series(1,10) AS s(i);
unfiltered | filtered ------------+---------- 10 | 4
0 notes