【问题标题】:Rails nested form, attributes not getting passedRails嵌套表单,属性未通过
【发布时间】:2012-08-19 22:45:51
【问题描述】:

所以我有一个Conversation 模型,它是has_many messages。创建对话时,我正在尝试创建新消息。这是我的ConversationsController

class ConversationsController < ApplicationController
  before_filter :authenticate_user!
  def new
    recipient = User.find(params[:user])
    @conversation = Conversation.new(from: current_user, to: recipient)
    @conversation.messages.build(from: current_user, to: recipient)
  end

  def create
    @conversation = Conversation.create(params[:conversation])
    redirect_to @conversation
  end
end

这是我的表格 (conversations/new.html.erb):

<%= form_for @conversation do |f| %>
  <%= f.fields_for :messages do |g| %>
    <%= g.label :subject %>
    <%= g.text_field :subject %>
    <%= g.label :content %>
    <%= g.text_field :content %>
  <% end %>
  <%= f.submit "Send" %>
<% end %>

问题:当我提交表单时,对话的消息被保存,但我在build 中指定为参数的tofrom 字段没有保存(它们为零)。但是,在此表单中填写的 subjectcontent 字段保存得很好。

我已经进行了一些挖掘...如果我在@conversation.messages 上的new 操作或new.html.erb 上执行puts,则消息似乎有to 和@ 987654338@。只有当消息到达create 操作时,这些字段才会消失。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 nested-forms nested-attributes


    【解决方案1】:

    更新:

    class ConversationsController < ApplicationController
      before_filter :authenticate_user!
      def new
        recipient = User.find(params[:user])
        @conversation = Conversation.new(to: recipient)
        @conversation.messages.build
      end
    
      def create
        @conversation = current_user.conversations.build(params[:conversation])
    
        # Set all the attributes for conversation and messages which
        # should not be left up to the user.
        @conversation.to = current_user
        @conversation.messages.each do |message|
          message.to = @conversation.to
          message.from = @conversation.from
        end
    
        redirect_to @conversation
      end
    end
    
    <%= form_for @conversation do |f| %>
      <%= f.hidden_field :recipient %>
      <%= f.fields_for :messages do |g| %>
        <%= g.label :subject %>
        <%= g.text_field :subject %>
        <%= g.label :content %>
        <%= g.text_field :content %>
      <% end %>
      <%= f.submit "Send" %>
    <% end %>
    

    您可能仍想在对话模型中验证收件人。

    【讨论】:

    • 好吧,我可以考虑从 Conversation 中删除 fromto,我认为这更有意义...考虑到在给定的对话中,我可以向您发送消息,而您可以给我发消息,每次都颠倒tofrom...
    • 两件事:除了隐藏字段,没有其他办法吗?另外,我将如何验证收件人?
    • 您需要某种方式来跟踪跨请求的收件人。您可以将其作为 URL 参数(可能作为嵌套资源)而不是使用隐藏字段。验证取决于您,这取决于您的应用程序。用户是否应该能够提交任何收件人 ID,或者收件人应该是对话的两个成员之一?一些 ActiveRecord 验证应该有助于检查您需要的任何条件。
    猜你喜欢
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多