Mio
Mio

Reputation: 1502

Format simple_form collection select

I would like to use grouped_collection_select but my data act differently.

I have for exemple Post that have_many comments. I can do Post.find(:id).comments but can't do Comment.find(:id).posts. Comment belongs to an author and author belongs to post.

I would like to add to my form a select filtered by comment author :

= grouped_collection_select(:post, :id, @posts, :comments, :title, :id, :author)

I know it's wrong but how can I invert it? For the moment it return me something like

<select name="posts[:id]">
  <optgroup label="Post 1 title">
    <option value="4536">Soica</option>
    <option value="56775">Bob</option>
  </optgroup>
  <optgroup label="Post 2 title">
    <option value="7897" selected="selected">Sandy</option>
    <option value="266">Sarah</option>
  </optgroup>
</select>

Is it possible to trick it and filter it by comments author ? Maybe grouped_collection_select is not the best solution?

Upvotes: 1

Views: 105

Answers (1)

max
max

Reputation: 101811

You could probably simplefy your relations and app considerably by declaring the relations as:

class Post < ActiveRecord::Base
  belongs_to :author
  has_many :comments
end

class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :author
  belongs_to :post
end

Database sketch

Note that in a belongs_to relation you need to use the singular form. So to go from comments to posts you would always use:

Comment.find(6).post

Not .posts. Its pretty unlikely that you want a many to many model where a comment may belong to many posts.

Writing a query on authors based on comments is a bit tricky but defiantly doable.

@authors = Author.includes(:comments)
                 .where(comments: { post_id: 7 })
                 .order(:name) # or however you want to sort it.

And you would create the input like so:

grouped_collection_select(
  :post, 
  :id, 
  @authors, 
  :comments, 
  :name, 
  :id, 
  :name
)

Upvotes: 3

Related Questions