【问题标题】:Rails: Automatically add username to new postRails:自动将用户名添加到新帖子
【发布时间】:2016-02-17 03:47:04
【问题描述】:

在我的帖子控制器中,我使用以下内容查看学生发布的不同帖子的用户 ID:

def new
  @post = current_user.posts.build
end

这非常有用。但是,如果我也能看到他们的名字和用户名,那会更有用。现在我让学生手动输入他们的名字。

如何让新帖子自动获取登录用户的用户名和姓名?

【问题讨论】:

  • 但是为什么帖子首先需要保存用户的username 和name?帖子属于用户,因此您可以通过@post.user.name 获取用户的姓名。一个帖子对象只需要保存user_id,然后使用关联,就可以得到用户的所有属性。

标签: ruby-on-rails posts


【解决方案1】:

要查看用户的username 和name 与@post 关联,您可以这样做:

username = @post.user.username
name     = @post.user.name

您应该经常去向@post 的user 询问属于该用户的属性。

【讨论】:

  • 谢谢。对于后代:除非我使用
【解决方案2】:

您也可以使用委托方法/委托模式described more here。 API 描述为here。

class Post < ActiveRecord::Base
  belongs_to :user
  delegate :username, :name, :to => :user
end

然后您可以调用:@post.username,这将返回用户的用户名。

【讨论】:

【解决方案3】:

我猜你正在使用 Devise。所以在_form.html.erb你可以这样显示用户名...首先,假设每个用户 has_one :Profile (:username, :first_name, :last_name)

这样 用户.rb

has_one :profile

profile.rb

belongs_to :user

在您的帖子表单中,您可以这样做 _form.html.erb

  <div class="field">
    <%= f.label :username %> : <%= current_user.profile.username %>
    or (if you define a method in your Model that will return your first_name and last_name)
    <%= f.label :full_name %> : <%= current_user.profile.first_and_last_name %>
    or
    <%= f.label :full_name %> : <%= current_user.profile.first_name %>  &nbsp; <%= current_user.profile.last_name %> 
  </div>

【讨论】:

  • 我想你已经假设了很多。
【解决方案4】:

带有您发布的代码的post创建将自动通过.user 关联方法获得user 的名称:

@post = Post.find x
@post.user.name #-> "name" of associated "user" model

由于您只发布了一个new 方法,并且已经提出了后续问题,所以我会为您编写一些代码:

现在我让学生手动输入他们的名字

为什么学生必须输入他们的名字?

ActiveRecord(和关系数据库)的全部意义在于提供对关联数据的访问;在users 表中存储user 详细信息(name 等),并通过posts 访问它。

这就是你对posts 控制器所做的事情:

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   def new
      @post = current_user.posts.new
   end

   def create
      @post = current_user.posts.new post_params
      @post.save
   end

   def show
      @post = Post.find params[:id]
      @username = @post.user.name
   end
end

这将自动为您的新post 设置user_id foreign key,这应该允许您使用@post.user.name 调用用户名

--

如果你想重构它,以避免law of demeter,你需要使用delegate方法作为Dewyze推荐:

#app/models/post.rb
class Post < ActiveRecord::Base
   belongs_to :user
   delegate :name, to: :user, prefix: true #-> post.user_name
end

Dewyze 的回答有点错误,因为他会产生 @post.name - 如果您想通过模型识别记录,则需要 prefix。

【讨论】:

  • 为了澄清,除了名称之外,该问题还要求提供用户名,因此不需要前缀。如果你有前缀 true,它最终会是 @post.user_username 和 @post.user_name。我指的是用户名一,尽管指出前缀很有用。
  • 很抱歉 - 你的代码仍然会创建 @post.name ;)
猜你喜欢
  • 2019-04-15
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多