Rails: How do you create a new nested resource?
In my app, Users have Conversations, and Conversations have Messages. A Message belongs both to a User (as an author) and to a Conversation.
I want to create a new Message. This is the code I'm using right now in MessagesController.
def new
@user = current_user #currently logged in user
@conversation = Conversation.find(params[:id])
@message = @conversation.messages.build
end
def create
@conversation = Conversation.find(params[:conversation_id])
@message = @conversation开发者_如何学编程.messages.build(params[:message])
if @message.save
redirect_to username_conversation(current_user, @message.conversation)
else
redirect_to root_url
end
end
params[:message] contains the message content ("content" => "I'm Spartacus").
This isn't working (probably because I'm not specifying the user/author when creating a new Message?). How do I make this work the Rails way?
Thanks.
You need to set the user manually. Only one property can be set using the short methods provided by Rails.
def new
@user = current_user #currently logged in user
@conversation = Conversation.find(params[:id])
@message = @conversation.messages.build
@message.user = user
end
def create
@conversation = Conversation.find(params[:conversation_id])
@message = @conversation.messages.build(params[:message])
@message.user = current_user
if @message.save
redirect_to username_conversation(current_user, @message.conversation)
else
redirect_to root_url
end
end
精彩评论