如何获取子ID的集合[Ruby on Rails 4.2]

时间:2016-03-10 11:37:13

标签: ruby-on-rails-4

我是Ruby on Rails的新手。

我有两个模特。

class Experience < ActiveRecord::Base
   has_and_belongs_to_many: assets
end

class Assets < ActiveRecord::Base
   has_and_belongs_to_many: experiences
end

在我的体验控制器中,我正在尝试获取与体验相关联的资产集合。 (亲子)

我目前正在使用will_paginate gem,并尝试为此构建一个集合以传递集合参数。

will_paginate(collection, options)

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您的模特关系应该是:

class Experience < ActiveRecord::Base
   has_many: assets
end

class Assets < ActiveRecord::Base
  belongs_to: experience
end

在Experience Controller中,获取相关资产

# single experience data
@experience = Experience.first
@experience.assets


# multiple experiences data
@experiences = Experience.all.includes(:assets)

# you can also use this in view
@experiences.each do |x|
  x.assets.each do |a|
    a.title (ex. field name)
    ...
  end
end