Context
When I generate the fixture file, rails generate model Post title:string text:text it shows:
one:
title: MyString
text: MyText
two:
title: MyString
text: MyText
Question
I was wondering why are there 2, and why are they named "one" and "two".
Here I see that names like "google", "rubyonrails", and "parent/child" are used; whereas, following the tutorial for generating the posts model, it generates just one and two...
Upon more research, I found that I might also be interested in db/migrate files. My current theory is that these files create the structure of my data... so I'm not so sure what fixtures does.
Reason
I'm trying to create a "Student" model using
rails generate scaffold student
but it doesn't seem to have :name as one of its keys. I'm looking into fixtures to add data columns.
Just some quick notes on your question:
Fixtures are data that you can feed into your unit testing. They are automatically created whenever rails generates the corresponding tests for your controllers and models. They are only used for your tests and cannot actually be accessed when running the application.
By default, Rails provides two fixtures named 'one' and 'two' every time. You can change them as you so please, Also, the data that goes into the fixtures is made when you pass in the keys for the database columns you want when using the generator. In the the first example were you used rails g model Post title:string... you created a model called Post and passed in two keys: :title and :text.
Answer:
As for your last question, you can quickly resolve the issue by
a) Deleting the old scaffold by typing the following in your command line:
rails d scaffold Student
b) Creating it again but this time with the keys you want:
rails g scaffold Student name:string
I'll start by saying that the code generated by the rails generate command is intended to be a starting point for parts of your application, helping you get going quickly.
That said - fixtures are intended for use in unit tests. They give you a way to generate a set of objects already existing in the system, so you don't have to create them by hand at the beginning of your test.
In this case, one and two are just placeholders. In a real app, you'd replace them with names that were more meaningful in your tests.
If you're looking to add columns of data in your app, fixtures probably aren't the right approach. They're really meant for use in tests, nothing more.
Try this:
As for your last question, you can quickly resolve the issue by a) Deleting the old scaffold by typing the following in your command line:
rails d scaffold Student
b) Creating it again but this time with the keys you want:
rails g scaffold Student name:string
Related
I'm starting out with ruby and rails, it's my 1st day, reading the guides.
I'm trying to generate a scaffold with various models, for instance Game and Platform. I'm trying to replace an existing, way outdated Symfony PHP project and picked Ruby/RoR for learning purposes, also because I was impressed with hotwire from the blog demo video.
A Game has_one Platform, a Platform has_many Games.
Or
type Game {
id: ID!
name: String
slug: String
platform: Platform!
}
type Platform {
id: ID!
name: String
slug: String
games: [Game]
}
For now I'd like to generate those 2 models with "rails g scaffold". I read on other questions that one has to use ":references" but I can't find that keyword anywhere in any guide of activerecord.
rails g scaffold Game name:string slug:string platform:references
is what I have so far. Is it even possible to define associations with foreign keys via the cli?
What is the typical workflow when generating models/scaffolds? Do you just start with the bare minimum of the model and manually edit the migration, add fk and associations?
I guess I'm more looking for a discord server for ruby/rails/other. I have so many questions but don't feel like this belongs here, because I would create question after question. But for now let's stick to this. (Side question, what is the de-facto standard when it comes to authn/z in rails? And another question, is there somelike that auto-slugifies, see the name and slug connection?)
The question is how to express model associations on the command line?
Is it even possible to define associations with foreign keys via the cli?
Yes.
You can define belongs_to assocations via the generators - as its the only assocation thats actually backed by a database column on this models table. You cannot define has_one, has_many or has_and_belongs_belongs_to_many via the generators - they must be added to the model later.
For now I'd like to generate those 2 models with "rails g scaffold". I read on other questions that one has to use ":references" but I can't find that keyword anywhere in any guide of activerecord.
It is not really a keyword. Rather references/belongs_to (the later is an alias) are column types (well kind of) when generating models or migrations.
If you run rails g model -h it details the options:
You can also consider references as a kind of type. For instance, if
you run:
bin/rails generate model photo title:string album:references
It will generate an album_id column. You should generate these kinds
of fields when you will use a belongs_to association, for instance.
It also adds belongs_to :album in the model when you use it with the model generator.
What is the typical workflow when generating models/scaffolds? Do you just start with the bare minimum of the model and manually edit the migration, add fk and associations?
Scaffolds are mainly useful for rapid prototyping or when you're learning as way to see the "Rails Way" of defining resources. They tend to generate way more code then you actually need and will outrun your tests.
Generators in general are just a tool and its often easier and faster to just edit the resulting files then to get the exact invokation of the generator right.
I creating an app that needs to be able to create and drop tables on the fly, on create it's pretty simple I use:
rails g model User name:string
but there is no generator for dropping a table.
I want to make it be possible to:
rails g migration DropTableUser
To correct your question, rails g migration User name:string would result in a migration called User not a model, I guess what you meant was rails g model User name:string.
To answer your question, I think it would result in an unnecessary mental effort, especially since something like this already exists in:
rails [d|destroy] model User
If you want to still implement yours, I'd advise that you look at Rails Generators instead for a way to help you out. I guess that would be dependent on creating a migration template etc.
I want to create a model with many fields on rails. I want two of the ten fields to have two or three options to choose from to check off.
The guide I'm using has only two fields, as follows:
rails generate scaffold topic title:string description: text.
It seems like the easy way out is to do a migration in this format:
rails generate migration AddClosing_Hrs1ToBusinesses closing_hrs1:string new_cloumn:string third_column:string
(source: How to add several columns to a database in Rails).
Any advice?
It depends on where you are in the process.
If you have not yet created the model at all you can just add more fields to the original generate scaffold line. For example if you wanted 4 fields:
rails generate scaffold topic title:string description:text another_item:string some_number:integer
If you already created the model but have not yet run rake db:migrate then you can find the migration file in app_name/db/migrate/. Open the file and add lines for your new fields
If you have already run db:migrate then you should follow the answer for "How to add several columns to a database in Rails" that you linked in your answer.
For the fields where you want several options to select from those options will need to be handled by a combination of your model and view code. Assuming the options will stay constant and you can only select one first define the options array in your model using something like:
OPTIONS_FOR_TITLE = ["Title 1", "Title 2", "Title 3"]
Then in the view code you will use the select and options_for_select helpers to create the view. More details on them are available here:
http://guides.rubyonrails.org/form_helpers.html#the-select-and-option-tags
For lots of detailed information about migrations:
http://guides.rubyonrails.org/migrations.html
I'm creating a simple webapp that tracks calories as a way to learn Ruby on Rails. I'm using the gem devise for users to sign in. My next step is to generate a model. I was going to use:
rails generate model Tracker calories:integer consumed_on:datetime
The problem though is that I don't know how to relate this data to the signed in user. What am I missing from this generate model command?
rails generate model Tracker user_id:integer calories:integer consumed_on:datetime
This will generate your model with a foreign key in the database referencing the user table.
Of course this is not all you have to do, you have to put other code in your model and controller to combine those two columns, create the views, update the config/routes.rb file ..
Also:
Don't forget to run the rake db:migrate to make the relational table in the database.
You can see how its done here (your Tracker model/table is theirs Micropost):
http://ruby.railstutorial.org/chapters/a-demo-app#sec-microposts_resource
All of the tutorials I've seen so far for RoR have shown me generating models like:
rails generate User name:string placeofbirth:string
This generates a class for the model, and only actually references an attribute if I apply a validation of some kind.
So my question is, how do I use a 'code' first approach when creating my models. Or is it the rails way to just right down on paper the attributes you want, run the generate command with each attribute you want and it's type, then run the rake db:migrate command?
I'd love some more proven patterns on this subject because so far the way I've seen seems too empty.
Yes, this is the rails way- migration comes first and generates the code and the database- and the model class inspects the database to see what fields are there and make accessible via methods.
You can do gem install annotate_models if you want to get some comments in your model class with the attribute names and types.
See here for an example: https://github.com/ctran/annotate_models
Rails uses an active record pattern for models which basically means that a model object will automatically map each DB column to an attribute so you don't have to specify all attributes in the model. It's a feature, but I agree that it might not be perfect for everyone. If you're using Rails 3 it should be easy to use another ORM of your choice if ActiveRecord's approach doesn't suit you. Here are some alternative ORMs that you could use.
Usually when you are developing some database backed web application, you know the database design(name of the tables, name of the columns in those tables and associations between different tables) beforehand.
Rails, as mentioned by maarons in his answer, uses Active Record pattern. Your models are classes that represent a table in your database, an instance of your model class a row in that table and different attributes of an object represent values under different columns in the same table.
When you create a model, usually, you are creating a class that represents one of the tables in your database. And while you are creating a model, you are also going to create a table in your database. That means knowing the name of the table and columns within that table.
So to answer your question, you must know all the columns, required for the time being, that will be in your tables. And hence available as attribute methods for your model objects. You specify these columns to added in the table in the migration generated by rails generator while generating this model. This is what usually everyone does.
You can take a code first approach by creating a class, without running the rails model generator,under app/models/ but not inheriting it from ActiveRecord::Base. As you move forward in your development, you can generate migrations by $ rails generate migration MigrationName and creating table and adding columns using [add_column][2]to that table as required. Once you have created a table for this model, you will have to inherit that model from ActiveRecord::Base so that you can get all the Rails magic in your application.