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



我是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)

我该怎么做?

您的模型关系应为:

class Experience < ActiveRecord::Base
   has_many: assets
end
class Assets < ActiveRecord::Base
  belongs_to: experience
end

在体验控制器中,获取关联的资产

# 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

最新更新