0

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
Mike Earley
  • 1,223
  • 4
  • 20
  • 47
  • shouldn't it be id in place of tag_id like this:@chat.taggings.create(id: params[:tag_id], coordinator: current_coordinator) – Ankit Bansal Feb 19 '16 at 14:37
  • didn't work...which makes sense, because it doesn't match the table columns. That would imply that I want the ID of the taggings table to be tag_id, but in fact (as you see in the updated table columns) I want tag_id = tag_id. ID itself should be auto-gen. – Mike Earley Feb 19 '16 at 16:03

1 Answers1

2

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)
MilesStanfield
  • 4,571
  • 1
  • 21
  • 32