【问题标题】:Assigning a User Id to a Nested Model将用户 ID 分配给嵌套模型
【发布时间】:2015-05-16 02:09:07
【问题描述】:

在设计中使用 Rails 4

我有一个 Post 模型和一个 Comment 模型。评论嵌套在帖子中。我已将帖子分配给用户,但由于它是嵌套的,因此无法将 cmet 分配给用户。

routes.rb

resources :posts do
  resources :comments
end

用户.rb

has_many :posts
has_many :comments

post.rb:

has_many :comments
belongs_to :user

comment.rb:

belongs_to :post
belongs_to :user

在我的 cmets_controller.rb 中,我尝试过像这样使用 current_user:

def new
  post = Post.find(params[:post_id]
  @comment = current_user.post.comments.build

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @comment }
  end
end

def create
    post = Post.find(params[:post_id])
    @comment = current_user.post.comments.create(comment_params)

    respond_to do |format|
      if @comment.save
        format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
        format.xml  { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

但我收到此错误:

undefined method `post' for #<User:0x00000103300a30>

解决此问题的最佳方法是什么?

【问题讨论】:

  • 不应该是帖子

标签: ruby-on-rails ruby ruby-on-rails-4 devise


【解决方案1】:
@comment = post.comments.build

而不是

@comment = current_user.post.comments.build

这样不行。

您已经告诉它post 是什么,那么您是否希望current_user.post 返回不同的东西?

def create
  post = Post.find(params[:post_id])
  @comment = post.comments.create(comment_params)
  @comment.user = current_user

  respond_to do |format|
    if @comment.save
      format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
      format.xml  { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
    end
  end
end

而不是

def create
  post = Post.find(params[:post_id])
  @comment = current_user.post.comments.create(comment_params)

  respond_to do |format|
    if @comment.save
      format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
      format.xml  { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
    end
  end
end

【讨论】:

  • 是的,你是对的。如何将评论分配给用户?
  • 太棒了,谢谢。我还需要在新操作中包含@comment.user = current_user 吗?我不认为我这样做,但只是确保。我很抱歉我是 Rails 新手,仍然需要阅读 Rails 指南。
  • 不用担心。你是对的,current_user 在服务器端是已知的,所以把它放在新的操作中是没有用的。
猜你喜欢
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多