Rails表单创建空对象 - 嵌套资源

时间:2012-07-13 15:08:01

标签: ruby-on-rails ruby forms messaging

看了很多资源,似乎无法解决这个问题。

我正在使用BinaryMuse基于此代码的消息传递系统:

https://github.com/BinaryMuse/so_association_expirement/compare/53f2263...master

它没有响应功能,所以我正在尝试构建它。

我将以下代码添加到UserConversations控制器:

def update
    @user = User.find params[:user_id]
    @conversation = UserConversation.find params[:id]
    @conversation.user = current_user
    @message = @conversation.messages.build
    @message.conversation_id = @conversation
    @message.save
    redirect_to user_conversation_path(current_user, @conversation)
end

以下是UserConversations#show view:

<%= form_for(@conversation) do |f| %>
<%= f.fields_for :messages do |m| %>
    <div>
        <%= m.label :body %><br />
        <%= m.text_area :body %>
    </div>
<% end %>
<%= f.submit %>

使用我所拥有的,创建一个具有正确conversation_id的新消息。但是,它没有附加body或user_id。

任何想法我做错了什么?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

BinaryMuse(我正在使用的原始代码的创建者)非常棒,可以查看他的旧代码并添加一些内容来回复。这有多棒?这是他的东西的链接:

Message System with Reply

P.S。感谢Patrick,我非常感谢您的见解!

答案 1 :(得分:0)

这些行使用正确的conversation_id创建新邮件。您的问题源于不涉及表单中传递的参数。

@message = @conversation.messages.build
@message.conversation_id = @conversation
@message.save

理想情况下,您可能需要执行类似

的操作
def update
    @user = User.find params[:user_id]
    @conversation = UserConversation.find params[:id]
    @conversation.user = current_user
    if @conversation.update_attributes(params[:conversation])
        redirect_to user_conversation_path(current_user, @conversation)
    else 
        render(:action=>'edit')
    end
end

让update_attributes处理更新'消息'。确保您在accepts_nested_attributes_for模型中指定了Conversation

有关详细信息,请查看

相关问题