Search code examples
ruby-on-railsrubyformsnested-resourceshtml-select

Rails 4 select_tag with nested resource


I have a resource that looks like this:

resources :teams do
  [...]
  get 'tags/:tag', to: "teams#show", as: :tag
end

Each Team can have multiple Posts which in it's turn can have multiple Tags. In my teams show view I want to display a select_tag that lists all the tags for the Team's Posts. When the user selects a tag I want to redirect them and list all posts for that tag. I have go it to work, but not with my nested resource and the URLs that I want. My implementation currently looks like this (I use HAML):

/ View
= form_tag team_path(@team), method: 'get', class: 'tag_form' do
  .input-group
    = select_tag "tag", options_from_collection_for_select(@team_tags, 'id', 'name', params[:tag]), prompt: "All tags", class: 'chosen-select'

# Controller

def show

  @team_tags = @team.posts.tag_counts_on(:tags)

  if params[:tag] && !params[:tag].blank?
    tag = Tag.find(params[:tag])
    @posts = @team.posts.tagged_with(tag.name)
  else
    @posts = @team.posts
  end

end

This works, but gives me an url that looks like this:

teams/1?utf8=✓&tag=1

What I want is:

teams/1/tags/tag-name

Is that possible to do, and how would that look?


Solution

  • Based on this answer, you might be able to get this to work:

    = select_tag "tag", 
      options_from_collection_for_select(@team_tags, 
      'id', 
      'name', 
      params[:tag]), 
      {prompt: "All tags", 
      class: 'chosen-select'}, 
      {onchange: "window.location.replace('/teams/' + @team.id + '/tags/' + this.value);"}
    

    the only thing i'm not sure about is if @team.id will interpolated correctly inside :onchange, so you could also try changing the onchange line to this:

    onchange: "window.location.replace('/teams/#{@team.id}/tags/' + this.value);"