0

我有一个模型中的项目列表,标签,我想在下拉字段中显示。用户将选择一个,它将被添加到 Chat 对象中。与 Chat::Tags 存在 1:many 关系,存储在 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并且 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 回答