Rails嵌套表单,属性未通过

时间:2012-08-19 22:45:51

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

所以我有一个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 %>

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

我已经做了一些挖掘...如果我在puts操作或@conversation.messages操作newnew.html.erb进行了操作似乎有tofrom。只有当邮件到达create操作时,这些字段才会消失。

1 个答案:

答案 0 :(得分:0)

更新:

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 %>

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