How to generate model fields on rails 4? - ruby-on-rails

I have run
rails generate Model Profile name:string
It have worked and generated all the files.
When I see the profile.rb file though it only has the class declaration not the fields.
class Profile < ActiveRecord::Base
end
Do I have to add all the fields manually ?

No, you don't to add fields manually. ActiveRecord will discover them at runtime from the table structure. This is part of rails magic :)

Related

How to pass class_name Option to Generator?

I am using Rails' generators to produce things like models in my app.
My models are commonly using the class_name option on relations.
Is it possible to generate a model from the command line and pass the value for class_name? I specifically want to avoid modifying the model after the generator runs.
An example of what I hope exists is something like:
rails generate model Book title:string author:belongs_to{class_name:User}
Then the generated Book model would look like:
class Book < ActiveRecord::Base
belongs_to :author, class_name: 'User'
end
No, you can't pass class_name as an option to the generator. It is not a valid option to the generator command. You can see the list of available options by running
rails g model --help
I believe the only way is to manually edit the models to specify the class_name

Rails user configurable migrations through views

I'm making a business administration Rails app.
Is there any info available on how I can enable admin users to add a new field to a table? Behind the scenes this would generate and run the migration and I guess some metaprogramming to include the field in the index, show and _form.html.rb views..
You can't run migrations like that, but you can solve the problem.
The answer is here
403-dynamic-forms
If you con't have a subscription, get one. Railscasts is gold for any rails developer
Basically you make a table in the database for the fields to a model.
For instance
class Product
has_many :product_fields
end
class ProductFields
belongs_to :product
end

How do you create a has_many association with multiple types?

I have the following:
a Link model
a LinkItem model, which I want to be of the following type
a comment
a tag
...
I am using this code:
Link model
class Link < ActiveRecord::Base
has_many :link_items
end
LinkItem model
class LinkItem < ActiveRecord::Base
belongs_to :link
end
class Comment < LinkItem
end
class Tag < LinkItem
end
Now I don't know how to tell Rails that my LinkItem model is supposed to be polymorphic. I've read the Rails Guide on asociations and other tutorials, but these just describe how to create a belongs_to association to multiple other models, not the other way around.
So my question would be:
How do I create a has_many association where the associated instances can be of different types? Or would it be better to create seperate models for comments, tags, etc. and just associate each of them individually with my Link model?
EDIT
Actually my code works.
I just tried using a 'type'-column (instead of 'link_item_type') in my database and rails automatically used it to save/determine the correct subclass of my LinkItems (thanks Wizard of Ogz for the hint)
However I still can't access the subclasses of LinkItem without referencing a LinkItem first. Is this some kind of lazyloading?
If you are looking for polymorphic association nicholaides has the right way .
If you are looking for has_meny polymorphic association , check out the answer to "Setting up a polymorphic has_many :through relationship".
This is called a polymorphic association. Here is some documentation.
I just dealt with what I think is the same issue.
My filename for my model was wrong. I initially created it with one name (ex. link_tag.rb), and then changed the name of the class (ex. from LinkTag to Tag) on the fly without changing the name of the file (ex. tag.rb).
When I renamed the file correctly, it worked as expected.
In summary, the name of the file needed to match the name of the class.
I know this post is a little old, but maybe that will help someone someday!
I user polymorphic associations a lot!
I would first watch this RailsCast and then the documentation suggested by nicholaides.
It perfectly explains how to create both sides of the association.

Where can I find the template of the Model that is generated by the scaffolder?

I want to costumize the Model generator/scaffolder that is used by rails e.g.:
rails generate model ModelName field:field_tyle,...
rails generate scaffold ModelName field:field_type,...
to pretend some areas and it should look like this when Im done cosutumizing the template.
class ModelName < ActiveRecord::Base
# ASSOCIATIONS
# VALIDATIONS
# ATTR RELATED STUFF
# INSTANCE METHODS
# CLASS METHODS
end
instead of:
class ModelName < ActiveRecord::Base
end
It was easy to find the View Templates used by the scaffolder but its not that easy to find the template for the Model. Where can I find it or is there "only" a generator for this and when how can I costumize it?
there is a guide on customizing rails generators Rails Guides. File location you can check at Rails API just need to know class name also you can check nifty generators by Ryan Bates
I had a similar issue it took some doing but this work for me.
The ActiveRecord model generator templates for Rails 3.1 go in:
lib/templates/active_record/model/
This could be either model.rb, migration.rb or module.rb
I imagine that DataMapper or MongoMapper go in analogous locations. Hope this helps.

How can I create references to objects in Ruby in ActiveRecords?

I am a Java developer I've been learning Rails for the past few days. I have a Java EE application (Uses Hibernate for ORM) that I am trying to port to Rails. I have used scaffolding to generate a few of my models. But I have other models which contain references to other models. How do I define the relations? Can I scaffold that as well?
Here is an example for what I am trying to do.
public class Engine {
private int valves;
private int capacity;
private int rpm;
}
I can scaffold the Engine class in ruby just by doing the following:
rails generate scaffold Engine valves:integer capacity:integer rpm:integer
Here is the tricky part for me:
public class Car {
private Engine engine;
}
How do I scaffold the Car class in Ruby?
If I understand correctly you are looking for associations. Here's a great guide
that you should read. The thing to understand here is that you define in your models how the they relate to each other with a series of methods described in that guide.
Here is what I would suggest you do:
rails generate scaffold Car <db columns>
rails generate model Engine valves:integer capacity:integer rpm:integer car_id:integer
In your two models:
class Car < ActiveRecord::Base
has_one :engine
end
class Engine < ActiveRecord::Base
belongs_to :car
end
You can actually generate scaffold for both models...that will create controller and views. But in this case it might make sense to add
accepts_nested_attribues_for :engine
to your Car model instead. This will allow you to manage the manipulation of the Engine model from the controller and views of the Car model.
At any rate, I hope this helps you start to find what you need.
You can do it using the references helper of activerecord migration.
rails generate scaffold Car engine:references ...
it will add :
t.references :engine in your migration file
has_many :engines in your Car model file
belongs_to :car in your Engine model file
Don't forget to check the rails api for options (default, relation callbacks...)(here for exemple : http://railsapi.com/doc/rails-v3.0.8rc1/)
You should learn more about Ruby. Ruby is not a static language, meaning every variable can hold every kind of object.
The rails generate command uses valves:integer etc. only for database purposes, because databases need this information.
Concerning your relations problem you should read about has_many, bleongs_to etc. (see http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html) In Rails you would define your relation like this
class Car
belongs_to :engine
end
class Engine
has_many :cars
end
Furthermore you have to add a foreign key engine_id to Car.
This works because there are several conventions used in Rails.
Without a basic tutorial you will not get far.
There is no scaffolding for relations, you have to learn how to do it "by hand" (which is not too demanding). Have a look at the "Rails Guides", and here "Active Record Association".
In your example, you have to do the following steps:
Create a migration to migrate the database: rails g migration AddIds
Modify the migration to include the additional ID you have to have:
...
add_column :engines, :car_id, :integer
Add to you models the following code:
class Car
has_one :engine
...
end
class Engine
belongs_to :car
...
end

Resources