Reputation: 101
Such as how to get data from another of the same model? http://guides.rubyonrails.org/ usually write as to establish a relationship between the models, but it is not clear in this case to get the data can consult books or online resources with examples?
Example:
class Foto <ActiveRecord :: Base
belongs_to: action
End
class Action <ActiveRecord :: Base
has_many: foto
end
ActiveRecord :: Schema.define (version: 20151207105829) do
create_table "actions", force:: cascade do | t |
t.text "name"
end
create_table "fotos", force:: cascade do | t |
t.text "fname"
t.integer "action_id"
t.text "image"
end
end
how to get the following SQL
SELECT * FROM fotos
INNER JOIN actions ON fotos.action_id = actions.id
Upvotes: 1
Views: 36
Reputation: 26
Rich Peck has completely right answer. But he should add that you can get all off the photos by using @action.fotos
after you will create some of them.
I.e. @action.fotos
will store all of your fotos which are belonging to some @action and will correspond to
SELECT * FROM fotos
INNER JOIN actions ON fotos.action_id = actions.id
Upvotes: 0
Reputation: 76774
This is a standard belongs_to/has_many
relationship -- you're looking to associate two models through a database reference.
--
You've already done the hard work - you have the relevant foreign_key
in your database (action_id
), which means you'll be able to do the following:
#config/routes.rb
resources :actions do
resources :fotos, only: [:new, :create]
end
#app/controllers/fotos_controller.rb
class FotosController < ApplicationController
def new
@action = Action.find params[:action_id]
@foto = @action.fotos.new
end
def create
@action = Action.find params[:action_id]
@foto = @action.fotos.new foto_params
end
private
def foto_params
params.require(:foto).permit(:fname, :image)
end
end
Upvotes: 1
Reputation: 2572
The below ActiveRecord statement should give you the fotos for a particular action
Action.find(name: "pass the name here").fotos
or if you wan to traverse in the opposite relation
Foto.find(fname: "pass the fname here").action
Note Your relationship is important, because you will need to pluralize the name of classes to fetch them accordingly.
Upvotes: 0