如何在每个帖子上显示“user_first_name”而不是“user_id”

时间:2016-06-14 19:46:17

标签: ruby-on-rails ruby

我想将每个新帖子分配给发布它的current_user

我设法显示帖子顶部发布的人员的user_id但是当我尝试使用user_first_name应用该流程时,它就无效了。我正在显示每个@post.user_id。我需要做些什么才能显示每个帖子的@post.user_first_name

这是Feed.controller:

before_action :require_user, only: [:index, :feed]

def feed      
  @posts = Post.all.order(created_at: :desc)
  @post = Post.new
end

def new
  @post = Post.new
end

def create 
   @post = Post.new(post_params) 
   @post.user_id = current_user.id

  if @post.save 
    redirect_to '/' 
  else 
    render 'new' 
  end 
end

private

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

这是CreatePost模型:

def change
  create_table :posts do |t|
  t.text :content
  t.integer  "user.id"
    t.timestamps null: false
   end
 end
end

这是CreateUser模型:

def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end

1 个答案:

答案 0 :(得分:0)

  

我想将每个新帖子分配给发布它的current_user。

http://apidock.com/rails/ActiveRecord/Associations/AssociationCollection/<<

在你的create方法中,你可以这样做

def create
  if current_user.posts << Post.new(post_params)
    redirect_to root_path #'/'
  else 
    render :new 
  end 
end
  

我需要做些什么才能显示每个帖子的@ post.user_first_name

执行此操作的最佳方法是在app/models/post.rb

中打开您的帖子模型
class Post < ActiveRecord::Base
  belongs_to :user

  delegate :first_name, to: :user, prefix: true
end

@post.user_first_name
  

我正在显示每个@ post.user_id

您能够执行此操作的原因是user_idpost表上的列,因此是Post类上的实例方法。但是user_first_name不是Post类的实例方法,而是User类。您可以使用委托创建您尝试使用的此方法。