标签: has-many-through

如何使用has_many:through和honor:conditions创建新记录?

假设我有一个课程,学生可以通过会员注册(例如课程和学生的has_and_belongs_to_many关系).有些会员资格适用于刚刚观看课程的学生(不是学分等),因此:

class Course < ActiveRecord::Base
  has_many :memberships

  has_many :students,
           :through => :memberships

  has_many :observers,
           :through => :memberships,
           :source => :student,
           :conditions => { :memberships => { :observer => true }}
end
Run Code Online (Sandbox Code Playgroud)

这是有用的:

observers = Course.find(37).observers
Run Code Online (Sandbox Code Playgroud)

这是不起作用的:

new_observer = Course.find(37).observers.build(:name => 'Joe Student')
Run Code Online (Sandbox Code Playgroud)

我原本以为可以使用该关联构建新记录,这将产生:

  1. 新学生记录('Joe Student')
  2. 新的会员记录(course_id = 37,student_id =(joe),observer = true)

但相反,我得到:

ActiveRecord::AssociationTypeMismatch: Membership expected, got Array
Run Code Online (Sandbox Code Playgroud)

我确信我对此如何完全感到困惑,并会欣赏任何见解!我也尝试在Membership模型上使用命名作用域执行此操作,但我似乎无法使用has_many在关联中使用作用域.

非常感谢您提供任何帮助!

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

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

使用关联(has_many)模型中的字段和rails中的formtastic

我搜索并尝试了很多,但我无法按照我的意愿完成它.所以这是我的问题.

class Moving < ActiveRecord::Base
  has_many :movingresources, :dependent => :destroy
  has_many :resources, :through => :movingresources
end

class Movingresource < ActiveRecord::Base
  belongs_to :moving
  belongs_to :resource
end

class Resource < ActiveRecord::Base
  has_many :movingresources
  has_many :movings, :through => :movingresources
end
Run Code Online (Sandbox Code Playgroud)

Movingresources包含其他字段,例如quantity.我们正在研究"账单"的观点.感谢formtastic通过写作简化整个关系的事情

<%= form.input :workers, :as => :check_boxes %>
Run Code Online (Sandbox Code Playgroud)

我得到一个真正漂亮的复选框列表.但到目前为止我还没有发现的是:我如何使用'movingresource'中的附加字段,在每个复选框的下一个或每个复选框下使用该模型中的所需字段?

我看到了不同的方法,主要是手动循环一个对象数组并创建适当的表单,使用:for in form.inputs part,or.但是这些解决方案都不是干净的(例如,用于编辑视图但不适用于新的,因为没有构建或生成所需的对象并且生成它们导致混乱).

我想知道你的解决方案!

ruby-on-rails has-many-through formtastic

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

Rails3通过问题嵌套has_many

我们计划将我们的应用程序升级到Rails3.我们使用过的一个插件是nested_has_many_through.这个插件似乎过时了,不再维护,并且似乎没有在新的Rails3应用程序中工作.

一个简单的例子:

Author.rb
has_many :posts
has_many :categories, :through => :posts, :uniq => true
has_many :related_posts, :through => :categories

Post.rb
belongs_to :author
belongs_to :category

Category.rb
has_many :posts
Run Code Online (Sandbox Code Playgroud)

任何人都可以推荐最好的练习方式来处理这个,或者一个工作的Rails3插件?

谢谢!!

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

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

Has_Many:通过或:finder_sql

我已经确定了我想要的东西,但我似乎无法以导轨设计师正在寻找的方式获得它.基本上,我有(请留出多元化/等问题):

人际关系(父母,后代)

我试图让单亲的所有后代,以及许多后代的单亲(假设每个后代只有一个父母).

我可以在模型中以下列方式执行此操作:

has_one     :parent, :through => :relationships, :foreign_key => :human_id, :source => :source_human
has_many    :offsprings, :finder_sql =>
          'SELECT DISTINCT offsprings.* ' +
          'FROM humans offsprings INNER JOIN relationships r on ' +
          'r.human_id = offsprings.id where r.source_human_id = #{id}' 
Run Code Online (Sandbox Code Playgroud)

我必须这样做,因为更好的方法:

 has_many    :offsprings, :through => :relationships, :foreign_key => :source_human_id, :source => :human
Run Code Online (Sandbox Code Playgroud)

是不可能的,因为在has_many中忽略了外键(根据这里的文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many)

但是,现在我收到了这个错误:

DEPRECATION WARNING:不推荐使用基于字符串的关联条件插值.请改用proc.因此,例如,has_many:older_friends,:conditions =>'age>#{age}'应更改为has_many:older_friends,:conditions => proc {"age>#{age}"}.(从(irb)的irb_binding调用:1)

但是,无论我如何破解:条件在这里,它似乎没有:finder_sql想要参与.有什么想法吗?

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

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

Ruby on Rails在保存之前通过关联对象具有很多功能

在Ruby on Rails项目上,我试图在将所有内容保存到数据库之前访问ActiveRecord上的关联对象.

class Purchase < ActiveRecord::Base

  has_many :purchase_items, dependent: :destroy
  has_many :items, through: :purchase_items

  validate :item_validation

  def item_ids=(ids)
    ids.each do |item_id|
      purchase_items.build(item_id: item_id)
    end
  end

  private

  def item_validation
    items.each do |item|
      ## Lookup something with the item
      if item.check_something
        errors.add :base, "Error message"
      end
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

如果我像这样构建我的对象: purchase = Purchase.new(item_ids: [1, 2, 3])并尝试保存它,item_validation方法没有填充项目集合,所以即使已设置项目设置,它也没有机会check_something在其中任何一个上调用方法.

是否可以在我的购买模型和关联模型持久化之前访问项目集合,以便我可以对它们运行验证?

如果我改变我的item_validation方法是:

def item_validation
  purchase_items.each do |purchase_item|
    item = purchase_item.item
    ## Lookup something with the item
    if item.something …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails has-many-through

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

has_many:通过NameError:未初始化的常量

我只想制作一个小连接表,最终在该连接上存储额外的信息(这就是为什么我不使用HABTM).从关联的rails文档中我创建了以下模型:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physicians
  belongs_to :patients
end
Run Code Online (Sandbox Code Playgroud)

我的架构看起来像这样:

ActiveRecord::Schema.define(:version => 20130115211859) do

  create_table "appointments", :force => true do |t|
    t.datetime "date"
    t.datetime "created_at",   :null => false
    t.datetime "updated_at",   :null => false
    t.integer  "patient_id"
    t.integer  "physician_id"
  end

  create_table "patients", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null …
Run Code Online (Sandbox Code Playgroud)

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

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

通过关联获取带有has_many的ActiveRecord :: RecordInvalid错误; 连接表上的验证问题

我有三个相关的模型,如下所示:

class Product < ActiveRecord::Base
  belongs_to :user
  has_many :descriptions, {
    dependent: :destroy,
    before_add: [:add_user_id_to_description, :validate_description]
  }
  has_many :documents, through: :descriptions

  # ...

  def validate_description(d)
    unless d.valid?
      d.errors[:user_id].each do |err|
        self.errors.add(:base, "Doc error: #{err}")
      end
    end
  end
end

class Document < ActiveRecord::Base
  belongs_to :user
  has_many :descriptions, {
    dependent: :destroy,
    before_add: [:add_user_id_to_description, :validate_description]
  }
  has_many :products, through: :descriptions
end

class Description < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
  belongs_to :document
end
Run Code Online (Sandbox Code Playgroud)

当我做的事情:

doc = user.documents.build
doc.update_attributes(:product_ids => [1,2])
Run Code Online (Sandbox Code Playgroud)

description验证失败,然后我得到false,并在适当的错误 …

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

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

Laravel多态关系有很多

我有一个订阅者模型

// Subscriber Model

id
user_id
subscribable_id
subscribable_type

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

public function subscribable()
{
    return $this->morphTo();
}
Run Code Online (Sandbox Code Playgroud)

和一个主题模型

// Topic Model

public function subscribers()
{
    return $this->morphMany('App\Subscriber', 'subscribable');
}
Run Code Online (Sandbox Code Playgroud)

我希望让所有用户通过订阅者模型,通知他们

通知::发送($ topic-> users,new Notification($ topic));

// Topic Model


public function users()
{
    return $this->hasManyThrough('App\User', 'App\Subscriber');
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

php relationship has-many-through laravel

9
推荐指数
4
解决办法
3357
查看次数

如何通过连接表填充has_many中的字段

我有一个关于活动记录关联的问题,请参考rails文档的这一部分:

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

如果我们有三个型号:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end
Run Code Online (Sandbox Code Playgroud)

文档说可以通过api以这种方式管理连接模型的集合:

physician.patients = patients
Run Code Online (Sandbox Code Playgroud)

但是,如果约会模型(如链接示例中)有一个名为appointment_date的字段,并且我想在特定日期为医生和患者创建新约会,该怎么办?以下代码将在约会表中创建一条记录,但是如何在第三步中填充appointment_date呢?

physician = Physician.first
patient = Patients.first
physician.patients << patient
Run Code Online (Sandbox Code Playgroud)

这样的事情存在吗?

physician.patients.create( :patient => patient, 'appointment.appointment_time' => appointment_time ) 
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails has-many-through

8
推荐指数
1
解决办法
3649
查看次数

Rails/ActiveRecord has_many through:未保存对象的关联

让我们使用这些类:

class User < ActiveRecord::Base
    has_many :project_participations
    has_many :projects, through: :project_participations, inverse_of: :users
end

class ProjectParticipation < ActiveRecord::Base
    belongs_to :user
    belongs_to :project

    enum role: { member: 0, manager: 1 }
end

class Project < ActiveRecord::Base
    has_many :project_participations
    has_many :users, through: :project_participations, inverse_of: :projects
end
Run Code Online (Sandbox Code Playgroud)

A user可以参与许多projects角色扮演a member或a manager.调用连接模型ProjectParticipation.

我现在在使用未保存对象上的关联时遇到问题.以下命令的工作方式与我认为应该有效相同:

# first example

u = User.new
p = Project.new

u.projects << p

u.projects
=> #<ActiveRecord::Associations::CollectionProxy [#<Project id: nil>]>

u.project_participations
=> #<ActiveRecord::Associations::CollectionProxy [#<ProjectParticipation id: nil, …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails has-many-through

8
推荐指数
1
解决办法
2127
查看次数