提取用户的ID并插入到ruby on rails上的Posts表中

时间:2014-08-02 18:08:54

标签: ruby-on-rails ruby

在rails上尝试使用ruby ..我在用户显示页面上添加了一个新的Post表单。(即0.0.0.0:3000/users/2)我正在尝试提取用户的id并将其插入到'user_id创建新帖子时,Post表格中的字段。因此,当从用户页面提交表单时,我可以将其链接到编写它的用户。

模型/ post.rb

class Post < ActiveRecord::Base

  belongs_to :user

  before_save :create_user_id

  def create_user_id
    self.user_id = current_user
  end
end

模型/ user.rb

class User < ActiveRecord::Base
  has_many :posts
end

助手/ application_helper.rb

module ApplicationHelper

  def current_user
    @current_user ||= User.find(params[:id])
  end
end

控制器/ post_controller.rb

class PostsController < ApplicationController

  def new
    @post = Post.new
  end

  def show
    @post = Post.find(params[:id])
    @page_title = @post.title.capitalize
    @author = User.find(@post.user_id)
    @author_url = "/users/" + @post.user_id.to_s
  end

  def create
    @post = Post.create(post_params)
    if @post.save
      redirect_to @post
    else
     render 'new'
    end
  end

  # private
  private

    def post_params
      params.require(:post).permit(:title, :body, :user_id)
    end
end

我得到的错误:

Couldn't find User without an ID

Extracted source (around line #15):  
  @post = Post.find(params[:id])
  @page_title = @post.title.capitalize
>>@author = User.find(@post.user_id)
  @author_url = "/users/" + @post.user_id.to_s
end

如果我测试并将我的application_helper.rb更改为此工作,则将2插入Post的user_id字段。当前设置只返回nil

module ApplicationHelper

  def current_user
    @current_user = 2
  end
end

1 个答案:

答案 0 :(得分:1)

首先,您想获得当前用户,现在您可以使用以下内容进行测试:

@current_user ||= User.find(2)

请注意,在创建调用中不会有:id参数:id表示资源的特定成员,因此在这种情况下,如果获取http://localhost:3000/posts/1个帖子将是资源而1将是param:id所以这不会返回你期望的current_user。

然后关联应该为您完成所有工作,并且不需要create_user_id方法。您所要做的就是将您的创建方法调整为

@post = current_user.posts.create(post_params)