【发布时间】:2014-05-10 20:00:53
【问题描述】:
我有items,每个都有多个(线程)comments。
线程是通过parent 键完成的,指向另一个comment。
我只是无法让create 操作正常工作,我已经将它提交到数据库中,但它没有设置item_id 和parent_id。
我试过form_for [@item, @comment]而不是form_for :comment, url: item_comments_path( @item ),但也没有用。
当我在 create 操作中查看 comment_params 时,我得到以下信息:
Parameters: {"utf8"=>"✓", "comment"=>{"body"=>"examplecommentgoeshere"}, "parent_id"=>"4", "commit"=>"Create Comment", "item_id"=>"4"}
谁能帮忙?
型号:
class Item < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
has_many :images, as: :item,
dependent: :destroy
validates :title, presence: true,
allow_blank: false
validates :description, presence: true,
allow_blank: false
validates :user, presence: true,
allow_blank: false
validates :layout, presence: true
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :item
has_many :responses, class_name: "Comment",
foreign_key: "parent_id",
dependent: :destroy
has_one :image, as: :item,
dependent: :destroy
belongs_to :parent, class_name: "Comment"
validates :body, presence: true,
allow_blank: false,
length: { minimum: 10 }
end
评论控制器:
class CommentsController < ApplicationController
before_filter :findParent
before_filter :find, only: [:update, :destroy, :show]
before_filter :is_logged_in?, only: [:create, :update, :destroy]
before_filter :has_permission?, only: [:update, :destroy]
def new
@comment = Comment.new
end
def create
logger.debug comment_params.inspect
@comment = current_user.comments.build(comment_params)
if @comment.save
redirect_to @item
else
logger.debug @comment.errors.inspect
session[:errorbj] = @comment
redirect_to @item
end
end
[...]
private
def comment_params
params.require(:comment).permit(:body, :parent)
end
private
def find
@comment = Comment.find(params[:id])
end
private
def findParent
@item = Item.find params[:item_id]
end
项目视图:
<p>
<h3>Add a comment:</h3>
<%= render partial: 'comments/form', locals: { parent: @item } %>
</p>
部分cmets/form:
<%= form_for :comment, url: item_comments_path( @item ) do |f| %>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.label :image %><br>
<nope>
</p>
<%= hidden_field_tag :parent_id, parent.id %>
<p>
<%= f.submit %>
</p>
<% end %>
从另一个 stackoverflow 线程我得出结论,在多关联中创建对象的唯一方法是按照以下方式执行操作:
@comment = current_user.comments.build( comment_params.join( { parent_id: <parent.id> } ) )
其他 stackoverflow 帖子却说不做
@item = Item.new( item_params.join( { user_id: current_user.id } )
那么真的没有更好的办法了吗?
【问题讨论】:
标签: ruby-on-rails activerecord model-associations nested-resources