我是铁杆新手。
请帮我如何创建rails一对一的关系。
我有两张桌子说abc和pqr。
在模型中,我在abc模型中声明了has_one:pqr
,在pqr模型中声明了belongs_to:abc
。我不知道如何为" pqr"编写视图和控制器。
答案 0 :(得分:2)
您可以使用
bin/rails generate controller Pqr hello
它将为视图生成一个控制器文件,一个视图文件,一个功能测试文件和一个帮助器。有关详细信息,请查看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
您可以在控件hello
pqr_controller.rb
处添加视图将使用的内容
class PqrController < ApplicationController
def hello
@content = "Hello World"
end
end
然后,如果您想要稍后对应的任何其他操作和视图,请说show
,您可以在控制器中添加操作并在app/views/pqr/show.html.erb
生成相应的视图
class PqrController < ApplicationController
def hello
@content = "Hello World"
end
def show
@contents = "Test"
end
end
答案 1 :(得分:1)
假设我们有2个表:person
和dog
首先,您需要在person_id
表格中创建dog
。
在模型中
比你在person.rb中添加has_on :dog
和dog.rb中的belongs_to :person
在控制器中
创建属于dog
的{{1}}。你需要先创建一个人。
person
然后创造他的狗。
@person = Person.new(params[:person])
@person.save
要访问某人的狗,您只需键入
即可@dog = Person.create_dog(params[:dog])
@dog.save