标签: has-many-through

检测rails中的变化has_many:通过关系

我有一个模型有许多has_many和has_many:通过模型关系.例如,在我的User类中,我有:

has_many:语言,通过:: profile_languages

我想要的是能够使用'User.changes'函数检测何时添加或删除它们,该函数返回使用User.language_ids =函数调用时已更改的属性数组.

有没有其他人试图这样做,或有这方面的经验?

有关ActiveModel更改功能的信息:http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

编辑:根据要求,这是我正在做的.

分配用户的属性后,在保存之前,我会查看.changes返回的所有值,以便记录外部日志中所做的所有更改.

所以如果我叫u.name ="新名字"

然后u.changes返回{name:['old name','new name']}

但是,当我向用户传递一堆语言ID时,例如

u.language_ids = [4,5]

然后创建了许多ProfileLanguage模型,并且u.changes哈希留空.

我试图在ProfileLanguage模型中创建一些回调,手动创建某种哈希,但我想知道这是否确实是最好的解决方案.

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

10
推荐指数
1
解决办法
3334
查看次数

HasManyThrough具有多态和多对多关系

在我的Laravel应用程序中,我有以下类:

class Product extends Model
{
    public function extended()
    {
        return $this->morphTo();
    }

    public function users {
        return $this->belongsToMany('App\User', 'products_users', 'product_id');
    }
}

class Foo extends Model 
{
    public function product()
    {
        return $this->morphOne('App\Product', 'extended');
    }
    public function bars()
    {
        return $this->hasMany('App\Bar');
    }
}

class Bar extends Model 
{
    public function product()
    {
        return $this->morphOne('App\Product', 'extended');
    }

    public function foo()
    {
        return $this->belongsTo('App\Foo');
    }
}

class User extends Model
{
    public function products()
    {
        return $this->belongsToMany('App\Product', 'products_users', 'user_id');
    }
} …
Run Code Online (Sandbox Code Playgroud)

many-to-many has-many-through laravel eloquent

10
推荐指数
1
解决办法
1197
查看次数

在Rails中使用改造gem,如何填充has_many:通过嵌套模型

我有一个用户模型和角色模型,通过以下方式连接到ActiveRecord:

has_many roles, through: :role_accounts
Run Code Online (Sandbox Code Playgroud)

我希望有一个"编辑用户"屏幕,其中包含一个复选框列表,每个角色一个.使用Reform gem(v2.1.0),这是表单对象的一个​​片段:

class UserForm < Reform::Form
  property :name
  collection :roles do
    property :id
  end
end
Run Code Online (Sandbox Code Playgroud)

我的问题是,当提交编辑表单,并检查2个角色时,params哈希看起来像:{"user=>{"name"=>"Joe","roles"=>["2","5",""]}}我收到此错误:

[Reform] Your :populator did not return a Reform::Form instance for `roles`.
Run Code Online (Sandbox Code Playgroud)

如何为has_many设置populator?

此外,我认为我首先需要删除所有用户的角色,然后添加所选的角色,这样他们最终只能使用当前的一组角色.我怎么能用改革宝石做到这一点?

ruby-on-rails has-many-through reform

10
推荐指数
1
解决办法
616
查看次数

在最后一次has_many之后销毁关联:通过记录被删除

使用常规has_many,可以选择:dependent => :destroy在删除父记录时删除关联.有了has_many :through,可能还有其他父母与子记录相关联,因此:dependent => :destroy没有任何效果.

如何确保子记录在从最后一个HMT关联中孤立后被删除?

activerecord ruby-on-rails has-many-through

9
推荐指数
1
解决办法
4236
查看次数

Setting a :has_many :through association on a belongs_to association Ruby on Rails

I have three models, each having the following associations:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
  has_many :model3s, :through => :model1  # will this work? is there any way around this?
end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many :model2s, :through => :model1  # will this work? is there any way around this?
end
Run Code Online (Sandbox Code Playgroud)

As you can see in the commented text, I have mentioned what I need.

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

9
推荐指数
1
解决办法
5844
查看次数

HMT collection_singular_ids =删除连接模型是直接的,不会触发销毁回调

刚遇到has_many问题:通过关联和after/before-destroy回调没有被触发.

说,我有用户,组和称为成员资格的中间关系.我有一个表单,允许用户通过在关闭相关复选框时创建新的成员资格记录来注册成组.基本上是一组group_id.

看起来像这样:

Which group would you like to join? (check all that apply)
[] Group A
[] Group B
[] Group C
Run Code Online (Sandbox Code Playgroud)

我希望记录一些操作,例如加入一个小组或将一个小组留在活动日志表中,并做一些其他不太重要的问题.

我有以下定义:

class Group < AR::Base
  has_many :memberships
  has_many :users, :through => :memberships
end

class Membership < AR::Base
  belongs_to :user
  belongs_to :group

  after_create :log_event_to_audit_table
  after_destroy :log_event_to_audit_table

end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships

  attr_accessible :group_ids   # enables mass-assignment
end
Run Code Online (Sandbox Code Playgroud)

创建新的成员资格记录时,after_create按预期运行.但是,after_destroy不会被触发!

在谷歌阅读并阅读文档后,我发现了原因:

"自动删除连接模型是直接的,没有触发销毁回调" - 来自Ruby Guides.

Hmmmmmm ...

因此,不会触发连接模型(在这种情况下为Membership)的销毁回调.嗯,这是一个下降.有什么理由为什么?

所以我的问题是解决这个问题的最佳方法是什么?我应该在User模型中定义我自己的membership_ed =方法直接调用membership.destroy吗?

对这种情况下的最佳实践提出任何建议.

谢谢!

activerecord ruby-on-rails has-many-through

9
推荐指数
1
解决办法
1209
查看次数

使用has_many:通过和构建

我有三个模型,全部用于has_many:通过关系.它们看起来像这样:

class Company < ActiveRecord::Base

  has_many :company_users, dependent: :destroy
  has_many :users, through: :company_users

  accepts_nested_attributes_for :company_users, :users

end

class CompanyUser < ActiveRecord::Base
  self.table_name = :companies_users #this is because this was originally a habtm relationship
  belongs_to :company
  belongs_to :user
end

class User < ActiveRecord::Base
  # this is a devise model, if that matters

  has_many :company_users, dependent: :destroy
  has_many :companies, through: :company_users

  accepts_nested_attributes_for :company_users, :companies

end
Run Code Online (Sandbox Code Playgroud)

这个加载很好,并且连接可以很好地用于查询.但是,每当我做某事时

@company = Company.last
@user = @company.users.build(params[:user])

@user.save    #=> true
@company.save #=> true
Run Code Online (Sandbox Code Playgroud)

无论是User记录和CompanyUser …

ruby ruby-on-rails has-many-through

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

find_or_create on a有很多关系

我的应用程序中有很多关系:

节目有很多乐队通过=> 阵容

乐队的独特之处在于:名字

class Show < ActiveRecord::Base
attr_accessible :city_id, :title, :dateonly, :timeonly, :image, :canceled, :venue_attributes, :bands_attributes

  belongs_to :city
  belongs_to :venue
  has_many :lineups
  has_many :bands, through: :lineups
  has_and_belongs_to_many :users
end


class Lineup < ActiveRecord::Base
  belongs_to :show
  belongs_to :band


end


class Band < ActiveRecord::Base
  attr_accessible :name, :website, :country, :state
  has_many :lineups
  has_many :shows, through: :lineups

  validates :name, presence: true
  validates_uniqueness_of :name
  before_save :titleize_name

  private
    def titleize_name
      self.name = self.name.titleize
    end

end
Run Code Online (Sandbox Code Playgroud)

新乐队的创建方式如下:

(假设我们已经保存了一个名为s1的节目记录)

> s1.bands.new(name: "Wet Food") …
Run Code Online (Sandbox Code Playgroud)

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

9
推荐指数
1
解决办法
3883
查看次数

升级到Rails 4.1后,新的多态关联与其父级一起保存时无效

从Rails 3.2升级到4.1后,以下的代码现在失败了:

在控制器/规范中:

post = user.posts.build
post.contacts << contact # contact is a persisted record
post.save! # now fails
Run Code Online (Sandbox Code Playgroud)

我基本上试图保存帖子及其相关的联系人,这应该是contact_publishment即时创建一个记录.错误在新contact_publishment记录上:"可发布不能为空"

该模型:

class Contact
  ...
  has_many :contact_publishments
  ...
end

class ContactPublishment
  ...
  belongs_to :publishable, polymorphic: true
  belongs_to :contact
  validates_uniqueness_of :publishable_id, :scope => [:contact_id, :publishable_type]
  validates_presence_of :contact, :publishable
  ...
end

class Post
  ...
  has_many :contact_publishments, as: :publishable
  has_many :contacts, through: :contact_publishments
  ...
end
Run Code Online (Sandbox Code Playgroud)

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

9
推荐指数
1
解决办法
856
查看次数

升级到Rails 4后:Specs在隔离传递时组合失败

我现在已经挣扎了很长一段时间了:我正在尝试应用程序从Rails 3.2 升级到Rails 4.虽然在Rails 3.2上所有规格都在通过,但它们在Rails 4中的某些条件下会失败.

有些规格在与其他规格一起运行时失败而且孤立的.

示例视频

https://www.wingolf.org/ak-internet-files/Spec_Behaviour.mp4(4分钟)

此示例视频显示:

  1. 使用:focus---绿色运行3个规格.
  2. 将它们与另一个规格一起运行 - 之前传递的两个规格现在失败了.
  3. 运行3个规格,但插入两个空行 - 一个规格失败.
    1. 使用后卫时,撤消无效.
    2. 焦点/焦点没有帮助.
    3. 重启后卫没有帮助.
    4. 运行所有规格,然后再次运行3规格确实有帮助,并使它们再次变绿.但是,添加其他任务再次导致两个规格失败.

可以看出,当与其他规格一起运行时,某些规格是红色的.即使输入空行也可以有所作为.

更多观察

  • 对于某些规范,运行多次时会随机发生传递或失败.
  • 该行为不是特定于一台开发机器,而是可以在travis上重现.
  • 使用database_cleaner在规范之间完全删除数据库没有帮助.
  • Rails.cache.clear的规格之间并没有帮助.
  • 将每个规格包装在一个ActiveRecord::Base.transaction没有帮助.
  • 这确实发生在Rails 4.0.0以及Rails 4.1.1中.
  • 使用这个最小的spec_helper.rb没有弹簧或任何东西都无济于事.
  • 直接使用后卫与使用bundle exec rspec some_spec.rb:123并没有什么区别.
  • 此行为适用于模型规范,因此不必对功能规范的并行数据库连接执行任何操作.
  • 我已经尝试在与(绿色)Rails-3.2分支相同的版本中保留尽可能多的宝石,包括guard,rspec,factory_girl等.---没有帮助.

更新:基于评论和答案的观察

rspec ruby-on-rails has-many-through ruby-on-rails-4

9
推荐指数
1
解决办法
612
查看次数