1

I'm trying to create a query to show every content of a section in my CMS.

The relation is one to many, one content has many sections.

Now I create a section controller and in the show method i receive the params[:id] of a section.

I must select all the contents where the content.section_ids array include my params[:id]

I know how to create the inverse query (where ID in array), but I cannot find a solution for this.

My query is:

@contents = Content.published.recent.where("#{params[:id]} IN (?)", ...)

Update

This is the relation.

I must select all the contents where the section is == to the section ID passed in my params.

class Content < ActiveRecord::Base
   has_many :sections, as: :sectionable
end

class Section< ActiveRecord::Base
  belongs_to :sectionable, polymorphic: true
end
1
  • it sounds like you've created a one-to-many relationship by making a Content have a section_ids field that's some kind of array or serialized array, rather than using a content_id foreign key on the sections table? Clearer information about the structure of your database is needed to adequately answer the question. What db are you even using?
    – gregates
    Mar 16, 2014 at 19:12

1 Answer 1

2
@contents = Content.published.recent.where(:id => params[:id])

Don't put params into where clause like ("id in (#{params[:id])") as it's vulnerable for sql injections. More details are here Rails SQL injection?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.