查看关联记录中存在的所有记录

时间:2019-04-17 07:50:44

标签: ruby-on-rails ruby

目标: 我想显示清单模型中当前存在的所有类别。

例如,一个列表可以具有许多类别。假设我有100个类别和10个列表,但Listing.category_ids中目前仅使用其中20个类别。

我已经尝试过:

@categories = Category.all.where(id: @listings.each {|listing| listing.category_ids})

@categories = Category.where(id: Listing.all.includes(:category_ids)).order(name: :asc)

@categories = Category.where(id: [@listings.each {|listing| listing.category_ids}])

和其他一些类似的方式。顺便说一句,我使用Postgres。

尽管未使用该类别,但这两种尝试都只出现在类别模型中的第一个类别。

型号:

列出

has_and_belongs_to_many :categories

类别:

has_and_belongs_to_many :listings

然后我也有了一个Categories_Listings连接表。这就是关联的存储位置。

1 个答案:

答案 0 :(得分:1)

您只需要加入即可。试试

var fieldName="UserField";
var fieldValue="update value here..."

var obj = {
             id: 123,
             [fieldName]: fieldValue
           };
var message="The field ["+ fieldName +"] will be updated with the value of ["+ obj[fieldName] +"]";  

这样,您应该只看到列表中具有匹配项的行

相关问题