All threads / How do I order by an associations serialised value?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I order by an associations serialised value?

Andre Zimpel asked in Rails

Folowing setup:

I got a rails app with dynamic content types. An user can create a content type and add fields (string, integer...) to it. Those are basically the smae like reugale rails models but they are managable through the app and the ui.

So I got:

class ContentType < ApplicationRecord
  has_many :content_type_fields
  has_many :content_entries
  has_many :content_entry_fields, through: :content_entries
end
class ContentTypeField < ApplicationRecord
  belongs_to :content_type
  has_many :content_entry_fields
  has_many :content_entries, through: :content_entry_fields
end

In addition to that I got content entries. The content entry belongs to an content type that defines the available fields. Plus there are content entry fields. They represent the content for a field for an entry.

class ContentEntry < ApplicationRecord
  belongs_to :content_type
  delegate :content_type_fields, to: :content_type
  has_many :content_entry_fields
end
class ContentEntryField < ApplicationRecord
  belongs_to :content_entry
  belongs_to :content_type_field

  serialize :value, JSON
end

I do serialize the value of the content entry field to enable localisation, e.g.: {"en-US":true,"de-DE":false}.

An example:

There is a content type called billboards. It has a content type field for title, link and link_color.
Based on the type let's say there are the following entries:

1, Shop, shop.example.com, black
2, Lookbook, lookbook.example.com, #eee
3, About Us, example.com/about-us, red.

Please keep in that the values in the database would be something like {"en-US":"About Us","de-DE":"Über uns"}.

Well, here comes the question:

How do I order all the entries based on the content entry field?

Something like: order all entries by title ASC or by link DESC.

I hope you get what I want to achieve. Basically I want to be able to dynamically create models through the ap ui, add entries based on that and then serve them through an api.

Thank you very much!

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,399+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.