Search code examples
ruby-on-railsformshamlcollection-select

Rails Select Drop Down with content from Controller not working


I've got a list of items in a model, Tag, that I want to show in a drop down field. The user will select one, and it will be added to the Chat object. There is a 1:many relationship with Chat::Tags, stored in a Taggings table.

So--A user selects a Tag from the drop down list and clicks "Add Tag", and the Chat page is refreshed, with the new Tag added to the Chat page (and stored in the Taggings table as foreign keys to Chat and Tag).

Here's what I have...

chats_controller.rb:

  def show
    @chat = Chat.find params[:id]
    @tags = Tag.order(:name)
  end

def update
  @chat = Chat.find params[:id]
  tagging = @chat.taggings.create(tag_id: params[:tag_id], coordinator: current_coordinator)
  flash[:success] if tagging.present?
end

And in show.html.haml:

.li
  = form_for @chat, url: logs_chat_path(@chat), method: :put do |f|
    = f.collection_select(:tag_id, @tags, :id, :name, include_blank: true)
    = f.submit "Add Tag"

Right now, it returns the following error:

"exception": "NoMethodError : undefined method `tag_id' for #<Chat:0x000000073f04b0>",

--edit--

The taggings table is:

["id", "chat_id", "tag_id", "coordinator_id", "created_at", "updated_at"]

And rake routes shows:

logs_chats GET    /logs/chats(.:format)  logs/chats#index
POST   /logs/chats(.:format) logs/chats#create
new_logs_chat GET    /logs/chats/new(.:format)  logs/chats#new
edit_logs_chat GET    /logs/chats/:id/edit(.:format) logs/chats#edit
logs_chat GET    /logs/chats/:id(.:format) logs/chats#show
PATCH  /logs/chats/:id(.:format)  logs/chats#update
PUT    /logs/chats/:id(.:format) logs/chats#update
DELETE /logs/chats/:id(.:format) logs/chats#destroy

Solution

  • The reason this doesnt work is because the form is for @chat and chat doesn't have a method called tag_id. The way it's called in the form is by the use of the f object. If you want to change/update taggings in that form...

    change your collection_select from this

    = f.collection_select(:tag_id, @tags, :id, :name, include_blank: true)
    

    to this

    = collection_select(:taggings, :tag_id, @tags, :id, :name, include_blank: true)
    

    and then in your controller change this

    tagging = @chat.taggings.create(tag_id: params[:tag_id], coordinator: current_coordinator)
    

    to this

    tagging = @chat.taggings.create(tag_id: params[:taggings][:tag_id], coordinator: current_coordinator)