Rails Select 下拉菜单中的内容无法正常工作

Rails Select Drop Down with content from Controller not working

我有一个模型 Tag 中的项目列表,我想在下拉字段中显示这些项目。用户将 select 一个,它将被添加到 Chat 对象中。与 Chat::Tags 存在 1:many 关系,存储在标签 table 中。

所以--用户 select 从下拉列表中选择一个标签并单击 "Add Tag",聊天页面刷新,新标签添加到聊天页面(并存储在Taggings table 作为 Chat 和 Tag 的外键)。

这是我的...

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"

现在,returns 出现以下错误:

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

--编辑--

标签 table 是:

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

并且佣金路线显示:

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

这不起作用的原因是因为表单是针对 @chat 的,而聊天没有名为 tag_id 的方法。它在表单中的调用方式是使用 f 对象。如果你想 change/update 这种形式的标签...

从这个

改变你的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)