标签: has-many-through

在has_many:through关系中指定外键

我有以下三个模型:用户,项目和分配.

用户has_many通过作业进行投射.但是,Assignment实际上有两个与User相关的外键:( user_id表示分配了项目completer_id的用户)和(表示完成项目的用户).

通常,user_id并且completer_id将是相同的(如果分配项目的用户完成它).但是,如果另一个用户完成它,user_id和completer_id将是不同的.

在我的用户模型中,我有以下内容:

class User < ActiveRecord::Base
  has_many   :assignments
  has_many   :incomplete_assignments, :class_name => 'Assignment',
    :conditions  => 'completer_id IS NULL'
  has_many   :completed_assignments, :class_name => 'Assignment',
    :foreign_key => 'completer_id'

  # this is the important one
  has_many   :incomplete_projects,
    :through     => :assignments,
    :source      => :project,
    :conditions  => 'completer_id IS NULL'
end
Run Code Online (Sandbox Code Playgroud)

我想创建一个名为的另一个关联,:completed_projectscompleter_id:through模型中用作User的外键,而不是:user_id.是否有可能做到这一点?

而且,顺便说一句,我知道这个:foreign_key选项.但是,使用时会忽略此选项:through,因此我想知道是否有办法在没有它的情况下执行此操作.

最后,我应该提到我对其他设计持开放态度,如果不能这样做,有人可以想出更好的方法.

model ruby-on-rails associations has-many-through

6
推荐指数
1
解决办法
9664
查看次数

ActiveRecord查询has_many:通过模型

如何在"has_many:through"关系中查询具有特定分支的公司

  #company.rb
  has_many :branch_choices
  has_many :branches, :through => :branch_choices
Run Code Online (Sandbox Code Playgroud)

"查找所有分行ID为3的公司"

activerecord has-many-through ruby-on-rails-3

6
推荐指数
1
解决办法
5999
查看次数

如何构建一个具有has_many关系的模型表单

我有一个Phrasehas_many PhraseTranslation.

应用程序/模型/ phrase.rb

class Phrase < ActiveRecord::Base
  has_many :translatabilities
  has_many :translations, through: :translatabilities
  has_many :inverse_translatabilities, class_name: "Translatability", foreign_key: "translation_id"
  has_many :inverse_translations, through: :inverse_translatabilities, source: :phrase
  accepts_nested_attributes_for :translatabilities
end
Run Code Online (Sandbox Code Playgroud)

应用程序/模型/ phrases_controller.rb

class PhrasesController < ApplicationController
  def index
    @phrases = Phrase.all.page params[:page]
    @translations = @phrases.count.times.map do |i|
      translation = Phrase.new
      translation.translatabilities.build
      translation
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我想为每个"短语"添加"可译性"形式.

应用程序/视图/短语/ index.html.erb

<table>
  <tbody>
  <% @phrases.each do |phrase| %>
      <tr>
        <td><%= phrase.text %></td>
      </tr>
      <tr>
        <td>
          <%= form_for @translations …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails has-many-through

6
推荐指数
1
解决办法
128
查看次数

如何通过特定字段对has_many进行排序

我有3种型号:member,team,和team_enrollment.结构如下:

class Member < ApplicationRecord
  has_many :team_enrollments    
  has_many :teams, -> {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollments
end

class TeamEnrollment < ApplicationRecord
  belongs_to :team
  belongs_to :member
end

class Team < ApplicationRecord
    has_many :team_enrollments
    has_many :members, through: :team_enrollments
end
Run Code Online (Sandbox Code Playgroud)

我试图做到这一点,当有人从一个成员(如此Member.first.teams)调用一个团队时,团队termination_date按照team_enrollments表中存在的属性按降序排序.我也想要它,如果它termination_date是零,它在订单的最后.我认为has_many :teams, -> {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollments上面的那条线会起作用,但事实并非如此.它似乎对订单没有影响.我该怎么改变?

顺便说一句,我在本地和生产中使用postgres.

activerecord ruby-on-rails has-many-through rails-activerecord ruby-on-rails-5

6
推荐指数
1
解决办法
256
查看次数

Rails类名称/类型不适用于多态has_many:through

我有一个管理借方和贷方的发票系统.基本上,发票金额是通过其借方总和获得的,余额是通过获取其贷方总额并将其减去总金额得出的.

我正在用四种型号做这件事.

  1. 发票
  2. 订单项
  3. 借方
  4. 信用

它的工作方式是通过一个连接模型(行项),它具有一个名为recordable的多态关联.乍一看似乎一切正常.但是,检查订单项会显示,当recordable_id显示正常时,recordable_type为nil.

这是代码的细分:

class Invoice < ActiveRecord::Base
  has_many :line_items, :dependent => :destroy
  has_many :debits, :through => :line_items, :as => :recordable
  has_many :credits, :through => :line_items, :as => :recordable
end

class LineItem < ActiveRecord::Base
  belongs_to :invoice
  belongs_to :recordable, :polymorphic => true
  belongs_to :credit, :class_name => "Credit", :foreign_key => "recordable_id"
  belongs_to :debit,  :class_name => "Debit",   :foreign_key => "recordable_id"
end

class Credit < ActiveRecord::Base
  has_many :line_items, :as => :recordable, :dependent => :destroy
end

class Debit < ActiveRecord::Base …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails has-many-through polymorphic-associations

5
推荐指数
1
解决办法
3703
查看次数

activerecord通过关联找到

我试图从我的数据库中检索一个activerecord对象.我的模特是

class User < ActiveRecord::Base
   belongs_to :account
   has_many :domains, :through => :account    
end
Run Code Online (Sandbox Code Playgroud)

class Account < ActiveRecord::Base
   has_many :domains
   has_many :users
end
Run Code Online (Sandbox Code Playgroud)

class Domain < ActiveRecord::Base
   belongs_to :account
end
Run Code Online (Sandbox Code Playgroud)

现在我想根据用户名和域名检索用户(假设这些是User和Domain类的属性).也就是说

User.find(:first, :conditions =>{:username => "Paul", :domains => { :name => "pauls-domain"}})
Run Code Online (Sandbox Code Playgroud)

我知道上面的代码不起作用,因为我必须提到有关表的一些内容.此外,用户和域之间的关联是一对多的(这可能使事情进一步复杂化).

关于如何形成这个查询的任何想法?

activerecord ruby-on-rails has-many-through

5
推荐指数
2
解决办法
2万
查看次数

创建或更新与has_many的关联:through

假设我有两个模型,Director和Movie,以及第三个名为Directions的连接模型.它们被定义为:

电影:

class Movie < ActiveRecord::Base
  has_many :directions
  has_many :directors, :through => :directions
end
Run Code Online (Sandbox Code Playgroud)

导向器:

class Director < ActiveRecord::Base
  has_many :directions
  has_many :movies, :through => :directions
end
Run Code Online (Sandbox Code Playgroud)

路线:

class Direction < ActiveRecord::Base
  belongs_to :movie
  belongs_to :director
end
Run Code Online (Sandbox Code Playgroud)

当我创建一部电影时,我希望能够使用提供的信息(名称和imdb_id)创建一个导演,或者根据imdb_id找到一个现有的导演,并将其与电影记录相关联.

从本质上讲,我不想删除或编辑导演.我只希望能够创建新的导演,如果他不存在基于他的imdb_id,或者在创建或编辑电影时与预先存在的导演关联.

我的问题是,如何在视图/控制器中链接所有这些?

accepts_nested_attributes_for工作正常,除非您在编辑我不想要的电影时可以实际编辑导演的名字.我完全没有兴趣更新/摧毁实际的董事,只有协会.

ruby ruby-on-rails associations has-many-through

5
推荐指数
1
解决办法
1117
查看次数

Rails has_many:通过自定义foreign_key

我有以下一套模型:

class Cardstock < ActiveRecord::Base
  has_many :color_matches, :primary_key => :hex, :foreign_key => :hex
  has_many :palette_colors, :through => :color_matches
end

class ColorMatch < ActiveRecord::Base
  belongs_to :palette_color
  has_many :cardstocks, :foreign_key => :hex, :primary_key => :hex
end

class PaletteColor < ActiveRecord::Base
  has_many :color_matches
  has_many :cardstocks, :through => :color_matches
end
Run Code Online (Sandbox Code Playgroud)

调用会Cardstock.last.palette_colors产生以下错误:

ActiveRecord::StatementInvalid: PGError: ERROR:  operator does not exist: character varying = integer
LINE 1: ...".palette_color_id    WHERE (("color_matches".hex = 66))  OR...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You …
Run Code Online (Sandbox Code Playgroud)

sql activerecord ruby-on-rails has-many-through

5
推荐指数
1
解决办法
2339
查看次数

Rails 3.2 - accepts_nested_attributes_for和join模型

我有以下型号:user,role,user_role(user_role是一个连接模型)

我正在尝试使用用户#edit页面上的复选框编辑用户的角色.这是我的尝试,我觉得我错过了一些重要的事情,或采取了错误的方法.

user.rb

has_many :user_roles, dependent: :destroy
has_many :roles, through: :user_roles

attr_accessible :user_roles_attributes

accepts_nested_attributes_for :user_roles, reject_if: lambda { |a| a[:role_id] == 0 }, allow_destroy: true

def has_role?(role_sym)
  roles.any? { |r| r.name.underscore.to_sym == role_sym.downcase }
end

def setup_roles!
  Role.all.each { |role|
    user_roles.build(user_id: id, role_id: role.id) unless has_role?(role.name.to_sym)
  }
end
Run Code Online (Sandbox Code Playgroud)

user_role.rb

belongs_to :user
belongs_to :role
delegate :name, to: :role
Run Code Online (Sandbox Code Playgroud)

role.rb

has_many :user_roles
has_many :users, through: :user_role
Run Code Online (Sandbox Code Playgroud)

users_controller.rb

def edit
  @user = User.find(params[:id])
  @user.setup_roles!
end …
Run Code Online (Sandbox Code Playgroud)

has-many-through nested-attributes ruby-on-rails-3

5
推荐指数
1
解决办法
2428
查看次数

建立A有一个通过vs有很多通过未保存的模型

我写了一个宝石,允许Google Spreadsheets转换成Rails模型.此过程的顺序包括创建所有模型,然后连接它们的关联,然后保存所有模型.它支持所有可用的关联类型,并且在每种情况下都禁止一个,创建模型,建立关联,然后保存模型正常工作.例外情况如下:

我有一个简单的has_one, through关联(为简洁省略了属性访问):

class Left < ActiveRecord::Base
   has_many :middles, dependent: :destroy
   has_many :rights, through: :middles
end

class Right < ActiveRecord::Base 
   has_one :middle, dependent: :destroy
   has_one :left, through: :middle
end

class Middle < ActiveRecord::Base
  belongs_to :left
  belongs_to :right
end
Run Code Online (Sandbox Code Playgroud)

我发现一些不一致的行为取决于关联分配的哪一方:

从左到右分配:

left = Left.new
right = Right.new
left.rights << right
left.middles #[]
right.middle #nil
left.save!
left.middles # <Middle theme_id: 1, archive_resource_id: 1 >
Run Code Online (Sandbox Code Playgroud)

从左到右分配:

left = Left.new
right = Right.new
right.left = left
left.middles #[]
right.middle <Middle theme_id: …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails associations has-many-through ruby-on-rails-3 has-one-through

5
推荐指数
1
解决办法
603
查看次数