在rails中为嵌套资源设置表单的位置和方式?

时间:2016-03-10 14:17:53

标签: ruby-on-rails forms

我有一个Idea模型,其中有一个Chat,当然,此聊天也有消息。 根据以下路线,我想在聊天页面中创建一个表单来发布消息。

# Chat belongs_to :idea, and Chat has_many :chat_messages
# I wan't to post messages to /idea/:id/chat/chat_messages
    resources :ideas do
        resource :chat, only: :show do
            resources :chat_messages, only: :create
        end
      end

目前,我的表单位于app/views/chats/show.html.erb,看起来像这样:

  # @chat and @chat_message are defined in Chat controller but I put them here so you can see them
  @chat = Chat.where(idea_id: params[:idea_id]).first
  @chat_message = ChatMessage.new(chat: @chat)

<%= form_for [@chat.idea, @chat, @chat_message] do |f| %>
    <%= f.text_area :body, size: "60x12" %>
    <%= f.submit "Message" %>
<% end %>

表单生成以下html(我删除了输入和一些不相关的内容):

<form action="/ideas/1/chat/chat_messages.1" accept-charset="UTF-8" method="post">
</form>

为什么我的表单操作中有.1(它会导致错误)。应该怎么样?我需要它来访问/ideas/1/chat/chat_messages

1 个答案:

答案 0 :(得分:0)

试试这个,

form_for [:idea, @chat, @chat_message]