Reputation: 65
I am new to rails.
Please help me how to create rails one to one relationship.
I have two table say abc and pqr.
in models I have declared has_one:pqr
in abc model and belongs_to:abc
in pqr model. I don't know how to write view and controller for "pqr".
Upvotes: 1
Views: 1051
Reputation: 2142
You could use
bin/rails generate controller Pqr hello
It will generate a controller file, a view file, a functional test file and a helper for the view,. For more information have a look at this article.
exists app/controllers/
exists app/helpers/
create app/views/pqr
exists test/functional/
create test/unit/helpers/
create app/controllers/pqr_controller.rb
create test/functional/pqr_controller_test.rb
create app/helpers/pqr_helper.rb
create test/unit/helpers/pqr_helper_test.rb
create app/views/pqr/hello.html.erb
You can add contents which will be used by your view, at your action hello
in the controller pqr_controller.rb
class PqrController < ApplicationController
def hello
@content = "Hello World"
end
end
Then if you want any other action and view corresponding to it later, say show
, you could add an action in the controller and generate corresponding view at app/views/pqr/show.html.erb
class PqrController < ApplicationController
def hello
@content = "Hello World"
end
def show
@contents = "Test"
end
end
Upvotes: 2
Reputation: 530
Lets say we have 2 tables: person
and dog
First of all you need to create a person_id
in dog
table.
In models
Than you add has_on :dog
in person.rb
and belongs_to :person
in dog.rb
In controllers
To create a dog
that belongs to a person
. You need to create a person first.
@person = Person.new(params[:person])
@person.save
then create his dog.
@dog = Person.create_dog(params[:dog])
@dog.save
To access a person's dog you just have to type
@person.dog
Upvotes: 1