Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing join table (A table without model) in rails

How to access the database table without the help of the model name?

for example if we have model(Post model),

@instance_var=Post.find(params[:id])

how can I access the database table that has no model ?

like image 719
Aarthi Avatar asked Nov 21 '17 04:11

Aarthi


2 Answers

2.8 Choosing Between has_many :through and has_and_belongs_to_many

The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database).

You should use has_many :through if you need validations, callbacks or extra attributes on the join model.

If you use Ruby on Rails instead of SQL you have the advantage of being compatible with most databases postgresql, mysql, sqlite etc...

You can easily migrate from mysql to postgresql, or viceversa..

like image 166
Fabrizio Bertoglio Avatar answered Oct 20 '22 15:10

Fabrizio Bertoglio


There is no harm in creating a Model for a table in Rails. Though, if you wish to avoid it, you can use raw SQL queries for same.

sql = "SELECT * from posts where id = #{params[:id}"
result = ActiveRecord::Base.connection.execute(sql)
result.to_a
like image 39
Aakanksha Avatar answered Oct 20 '22 16:10

Aakanksha