与连接表和多个别名的多对多关联

时间:2017-08-24 16:27:36

标签: ruby-on-rails ruby rails-activerecord model-associations

我正在开发一个地理缓存应用程序,用户可以在其中创建新缓存或访问现有缓存。以下是模型:

class User < ApplicationRecord
  has_many :usercaches
  has_many :visited_caches, source: :caches, through: :usercaches
  has_many :created_caches, class_name: :caches
end

class Cache < ApplicationRecord
  has_many :usercaches
  has_many :visitors, source: :users, through: :usercaches
end

class Usercache < ApplicationRecord
  belongs_to :user 
  belongs_to :cache 
end

联接表看起来像它的方式,因为我一直在努力消除任何与大写或复数相关的潜在错误。每当我在Rails控制台中创建User并尝试查看new_user.visited_caches时,我都会收到以下错误:

  

ActiveRecord :: HasManyThroughSourceAssociationNotFoundError:无法   找到源关联:模型Usercache中的缓存。尝试   'has_many:visited_caches,:through =&gt; :usercaches,:source =&gt;   ”。它是用户还是缓存之一?

但是,当我按照建议重新排列关联时,错误仍然相同。是否有一些我遗漏的小细节,或者我是否正在使用一个完全错误的范例来完成我想要完成的工作?

1 个答案:

答案 0 :(得分:1)

source必须以单数形式提供(has_many class User < ApplicationRecord has_many :usercaches has_many :visited_caches, source: :cache, through: :usercaches has_many :created_caches, class_name: :caches end class Cache < ApplicationRecord has_many :usercaches has_many :visitors, source: :user, through: :usercaches end class Usercache < ApplicationRecord belongs_to :user belongs_to :cache end 为其提供示例):

div>
      <h2>{{title}}</h2>
      <label class="form_label" for="account">Output Type</label>
      <div class="output_row_styles">
        <span><input type="radio" [value]="pdf" name="output"  (click)="outputType ='pdf'" [checked]="outputType =='pdf'"> PDF</span>
        <span><input type="radio" [value]="email" name="output" (click)="outputType ='email'" [checked]="outputType =='email'"> Email </span>
        <span><input type="radio" [value]="legal" name="output" (click)="outputType ='transfer'" [checked]="outputType =='transfer'"> Transfer</span>
      </div>
      <div *ngIf = "outputType == 'email' || outputType == 'transfer'" class="output_type_div">
          <div class="row_styles">
          <label class="form_label" for="recipient_email">Recipient E-mail address</label>
          <input type="text" [value]="outputType == 'transfer' ? 'abc@xyz.com' : ''" name="recipient_email" class="input-text"  [(ngModel)]="recipientEmailAddress"
            required/>
      </div>
    </div>