0

ドロップダウン フィールドに表示したいモデル タグのアイテムのリストがあります。ユーザーがいずれかを選択すると、Chat オブジェクトに追加されます。Chat::Tags とは 1 対多の関係があり、Taggings テーブルに格納されます。

つまり、ユーザーがドロップダウン リストからタグを選択して [タグの追加] をクリックすると、チャット ページが更新され、新しいタグがチャット ページに追加されます (そして、チャットとタグへの外部キーとしてタグ付けテーブルに保存されます)。 )。

これが私が持っているものです...

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

そして、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"

現在、次のエラーが返されます。

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

- 編集 -

タグ付けテーブルは次のとおりです。

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

また、rake ルートは次のように表示されます。

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
4

1 に答える 1

2

これが機能しない理由は、フォームが for で@chatあり、チャットに というメソッドがないためtag_idです。フォームで呼び出す方法は、fオブジェクトを使用することです。そのフォームのタグ付けを変更/更新したい場合...

これからあなたのcollection_selectを変更してください

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

これに

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

そして、コントローラーでこれを変更します

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

これに

tagging = @chat.taggings.create(tag_id: params[:taggings][:tag_id], coordinator: current_coordinator)
于 2016-02-19T16:40:50.413 に答える