Nested Models Creation
I am trying to build a nested model but I have a problem:
In new method in TopicController.rb
def new
@topic = Topic.new
@topic.message = Message.find(params[:id])
@topic.build_comment
end
And now in create I have (1st try):
def create
@cuser = current_facebook_user.fetch
@topic = Topic.new(:topic)
respond_to do |format|
if @topic.save
format.html { redirect_to(@topic, :notice => 'Topic was successfully created.') }
else
format.html { render :action => "new" }
end
end
en开发者_开发技巧d
Error for 1st try:
ActiveRecord::RecordNotFound (Couldn't find Message with ID=1 for Topic with ID=):
I also tried (2nd try):
def create
@cuser = current_facebook_user.fetch
@topic = Topic.new
@topic.message = params['topic']['message_id'] #enters nil instead of the message_id
@topic.comment = params['topic']['comment_id'] #enters nil instead of the comment_id
@topic.user = User.find(1) #enters correct user_id
respond_to do |format|
if @topic.save
format.html { redirect_to(@topic, :notice => 'Topic was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
Error for second try:
No Error but Topic.message_id = nill and Topic.comment_id = nill. Those values are not assigned.
Any suggestions?
Thanks
If message
and comment
are defined as associations in the Topic
model, you shouldn't assign IDs to them, but objects, like this:
@topic.message = Message.find(params[:topic][:message_id])
@topic.comment = Comment.find(params[:topic][:comment_id])
This only makes sense, of course, if both message
and comment
have already been created.
精彩评论