简体   繁体   English

Rails的:has_many通过

[英]Rails :has_many of a :has_one through

I am having issues setting up model relations in Rails. 我在建立Rails中的模型关系时遇到问题。

I have a User. 我有一个用户。 A user can have many requests. 一个用户可以有很多请求。 A request can have one response. 一个请求可以有一个响应。 I set up my models like this: 我这样建立模型:

Class User < ActiveRecord::Base
    has_many :user_requests
    has_many :request_responses, through: :user_requests
end

Class UserRequest < ActiveRecord::Base
    belongs_to :user
    has_one :request_response
end

Class RequestResponse < ActiveRecord::Base
    belongs_to :user_request
end

Whenever I try to do something like: 每当我尝试做类似的事情:

UserRequest.request_response.id

I get errors that say either the relationship doesn't exist or the column does not exist in the table. 我收到错误消息,指出该关系不存在或表中的列不存在。 Have I set up my relationships incorrectly? 我的人际关系设置不正确吗?

You will get error: 您将得到错误:

UserRequest.request_response.id

Because: 因为:

  1. request_response is expected to be a class method of UserRequest . request_responseUserRequest的类方法。
  2. Association is defined as request_responses , not request_response , so calling user. request_response 关联定义为request_responses ,而不是request_response ,因此调用user. request_response user. request_response won't work either. user. request_response也不起作用。

What to do? 该怎么办?

call user.request_response_ids where user = User.first . 呼叫user.request_response_ids ,其中user = User.first

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM