新手问题 关于一个表和多个表关联的问题请教,谢谢

justend · 2013年03月30日 · 最后由 tailang 回复于 2013年07月14日 · 2430 次阅读

刚刚学习 现在参照官方的 guild,做简单的 blog,post 和 user,comment 和 post 已经关联,但没搞定如何让 comment 和 user 同时关联。

问: 如何才能让生成的 comment 既有 user_id 也有 post_id 呢,谢谢

部分代码如下:

user.rb

has_many :posts
has_many :comments

post.rb

belongs_to :user
has_many :comments

comment.rb

belongs_to :post
belongs_to :user

comments_controller.rb 的 create 方法这样写的时候生成的 comment 有 post_id 没 user_id

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end

comments_controller.rb 的 create 方法这样写的时候生成的 comment 有 user_id 没 post_id

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

问: 如何才能让生成的 comment 既有 user_id 也有 post_id 呢,谢谢

1) 有 post_id 没 user_id: @comment.user = current_user 2) 有 user_id 没 post_id: @comment.post = @post

多谢回复,我试了以下的方式,还是没有效果,不知哪里出了问题,

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

在网上找到另外一种解决方法,已经可以了

def create
    @post = Post.find(params[:post_id])
    comment_attr = params[:comment].merge :user_id => current_user.id
    @comment = @post.comments.create(comment_attr)
    redirect_to post_path(@post)
  end

#2 楼 @justend@comment.user = current_user 之后 还要 save 一下才可以

@guyanbiao ha, 这样就可以了,谢谢了

@justend 你好请教个问题,我也遇到与你相同的问题,
我在 comments_controller.rb 这样写:

def create
      @comment = commentable_record.comments.create(params[:comment])
      @comment.user = current_user
      #current_user.comments.create(params[:comment])

      respond_to do |format|
        if @comment.save
          format.html {redirect_to commentable_record, notice: '创建评论成功'}
          format.json {render json: @comment, status: :created, location: commentable_record}
        else
          format.html { render action: :new }
          format.json { render json: @comment.errors, status: :unprocessable_entity }  
        end
      end
    end

然后我在 view 中这样访问:

<% @post.comments.each do |comment| %>
     <%= comment.user %><br>
     <%= comment.comment %><br>
     <% end -%>

这样的话 comment 中的内容可以正确显示,但是 comment.user 显示的不正确(见下图,上面是 user,下面是 comment 的内容),在我的 users 表中定义了 username 这个字段保存 user 的姓名,然后我将 comment.user 改成 comment.user.username,却提示没有 username 这个方法。请问你是如何在 view 中访问 user 的,如 name,age 等


需要 登录 后方可回复, 如果你还没有账号请 注册新账号