我在 Rails 4 中遇到关系问题。
有4个模型
- 用户
- 要求
- 制作
- 模特
一个用户有_多个请求,一个请求有_一个制造,一个制造有_多个模型。
User->Requests 和 Make->Models has_many 关系正常,但 Request->Make has_one 关系失败。
class Request < ActiveRecord::Base
belongs_to :user
has_one :make
end
class Make < ActiveRecord::Base
has_many :models
belongs_to :request
end
每个模型的模式是...
create_table "requests", force: true do |t|
t.integer "user_id"
t.integer "make_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "makes", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
当我尝试将 Make 分配给请求时,出现以下错误
Mysql2::Error: Unknown column 'makes.request_id' in 'where clause': SELECT `makes`.* FROM `makes` WHERE `makes`.`request_id` = 7 LIMIT 1
ActiveRecord::StatementInvalid Exception: Mysql2::Error: Unknown column 'makes.request_id' in 'where clause': SELECT `makes`.* FROM `makes` WHERE `makes`.`request_id` = 7 LIMIT 1
nil
为什么 ActiveRecord 在 Make 中需要一个 request_id?这难道不会像我在 User->Requests 和 Makes->Models 关系中那样仅适用于 has_many 关系吗?
最佳答案
has_one
和 belongs_to
方法允许您在模型之间创建一对一关联,因此允许您轻松访问每个模型其他通过各种辅助方法。
has_one
只应在其他类包含“外键”时使用。如果当前类包含“外键”,则应改用 belongs_to
。
根据您提供的架构,应该像以下示例中那样定义关联:
class Request < ActiveRecord::Base
# Because you have a `make_id` column in the "requests" table.
belongs_to :make
end
class Make < ActiveRecord::Base
# Because the Request model has the "foreign key" that
# creates the association, in this case `make_id`.
has_one :request
end
通过像上面的例子那样建立关联,Rails 将为您提供帮助方法,允许您访问或创建每个关联的模型:
# Request Model
@request = Request.create!
# Helper methods to access `make`: make, build_make, create_make, make=
@request.make
@request.build_make
@request.create_make
@request.make = Make.create!
# ...
# Make Model
@make = Make.create!
# Helper methods to access `request`
@make.request
@make.build_request
@make.create_request
@make.request = Request.create!
#...
我们使用 has_one
和 belongs_to
方法来创建关联,而且还可以访问 Rails 为我们创建的所有辅助方法。根据您是想从 Request 访问 Make 还是相反,您可以添加或删除 has_one 或 belongs_to 来自特定类(class)。
虽然每个类都保留在两个类中,但我们可以从双方访问一堆辅助方法。例如,如果您从 Request 中删除了 belongs_to :make
,您将无法使用 @request.make
从 Request 访问 make。但是,只要保留 has_one 方法,您仍然可以使用 @make.request
访问来自 make 的请求。
请记住,迁移是他们自己的事情,我们还需要通过将“外键”添加到正确的表来在数据库级别设置关联。通过查看 has_one 和 belongs_to 的定义,我们可以很容易地找出在何处添加外键。 has_one 表示“外键”应该在关联表中,belongs_to 表示它应该在this 表中。
希望对您有所帮助!这里有更多信息:
关于ruby-on-rails - has_one belongs_to Rails 4 中的关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219803/