简单的Rails博客 - 帖子评论忽略帖子ID [参数中的外部评论数组]

时间:2013-02-12 22:43:57

标签: ruby-on-rails ajax rails-activerecord

我有一个简单的博客,我正在使用Rails构建,我正在遵循正常的rails入门指南(http://guides.rubyonrails.org/getting_started.html)。我在帖子的show方法中设置了一个注释表单,但是当我保存时,它没有将page_id保存在注释记录中。

= form_for [@post, @post.comments.build], :remote => true do |f|

  .field
    = f.label :name
    = f.text_field :name
  .field
    = f.label :extra_field, @page.rsvp_extra_field
    = f.text_area :extra_field
  .actions
    = f.submit 'Save'

post.rb

class Post < ActiveRecord::Base

  has_many :comments, dependent: :destroy

  attr_accessible :comments_attributes, :comment_attributes

  accepts_nested_attributes_for :comments, :allow_destroy => true

end

comment.rb

class Comment < ActiveRecord::Base

  belongs_to :post
  attr_accessible :extra_field, :name, :post_id, :phone

end

我在rails控制台中看到它正在发布它,但是将NULL放在post_id上。有什么想法吗?

修改

我根本没有改变我的创建方法:

  def create
    @comment = Comment.new(params[:comment])

    respond_to do |format|
      if @comment.save
        format.html { redirect_to post_url, notice: 'Comment was successfully created.' }
        format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

编辑2

我认为我的参数是嵌套的,当我不希望它们是......任何想法如何在“comment”数组中得到这个“post_id”?

Parameters: {"utf8"=>"✓", "authenticity_token"=>"eqe6C7/ND35TDwtJ95w0fJVk4PSvznCR01T4OzuA49g=",
"comment"=>{"name"=>"test", "extra_field"=>""}, "commit"=>"Save", "post_id"=>"8"}

1 个答案:

答案 0 :(得分:0)

因为create中的方法CommentsController,创建与对象Comment无关的对象Posthas_many关系为相关对象提供了3种方法:

post.comments.create
post.comments.create!
post.comments.build(eq new method)

添加CommentsController这个:

  ...
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(params[:comment])
  end
  ...
相关问题