嵌套模型创建

时间:2011-08-02 15:22:36

标签: ruby-on-rails ruby ruby-on-rails-3

我正在尝试构建一个嵌套模型,但我遇到了一个问题:

TopicController.rb中的新方法

def new
  @topic = Topic.new
  @topic.message = Message.find(params[:id])
  @topic.build_comment
end

现在我正在创作(第一次尝试):

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
end

第一次尝试出错:

ActiveRecord::RecordNotFound (Couldn't find Message with ID=1 for Topic with ID=):

我也试过(第二次尝试):

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

第二次尝试出错:

No Error but Topic.message_id = nill and Topic.comment_id = nill. Those values are not assigned.

有什么建议吗?

由于

1 个答案:

答案 0 :(得分:0)

如果messagecomment被定义为Topic模型中的关联,则不应为其分配ID,而应为对象分配,如下所示:

@topic.message = Message.find(params[:topic][:message_id])
@topic.comment = Comment.find(params[:topic][:comment_id])

当然,如果已经创建了messagecomment,那么这只是有意义的。