无法将 current_user.name 作为评论的属性传递

Unable to pass current_user.name as an attribute for comment

以下解决方法:

    <%= f.label :Commenter %><br>
    <%= f.text_field :commenter, :value => current_user.name %>

这适用于将用户名传递给评论者属性而无需输入 - 额外的好处是可以在必要时对其进行编辑!


我正在尝试让我的网站显示创建评论的用户的姓名。为此,我希望将评论者(评论的属性)指定为 current_user.name.

评论有属性 commenter、body 和 expdate。

是否可以通过表单将current_user.name传递给comment.create方法?

我试过这个:

<div>
    <%= form_for([@project, @project.comments.build]) do |f| %>
        <br>

        **<%= @commenter = current_user.name %>**

        <%= f.label :Comment %><br>
        <%= f.text_area :body %>
        <br>
        <%= f.label :'Expected Date' %><br>
        <%= f.date_select :expdate %>
        <br>
        <br>
        <%= f.submit %>
    <% end %>
</div>

我将评论者属性指定为 current_user。这不是将其传递给创建方法吗?

我也试过在 comments_controller 中这样分配它:

def create
    **@comment.commenter = current_user.name**
    @project = Project.find(params[:project_id])
    @comment = @project.comments.create(comment_params)
    redirect_to project_path(@project)
end

但是我收到一个错误,抱怨评论者不是定义的方法。

我试过的两种方法都不允许我创建评论,有人知道我该怎么做吗? 非常感谢!

在控制器中,像这样:

def create
  @project = Project.find(params[:project_id])
  @comment = @project.comments.create(comment_params)
  @comment.commenter = current_user.name
  redirect_to project_path(@project)
end

并且在视图中:

<% @project.comments.each do |comment| %>
  <tr>
    <td><%= comment.body  %></td>
    <td><%= comment.commenter %></td>
    </td>
  </tr>
<% end %>

您可以在控制器的创建方法中执行此操作:

@commenter = current_user.name

就这么简单。如果您需要在您的视图中访问评论者姓名,请将其添加到您的评论中 class:

def commenter(user)
  user.name
end

那么在你看来:

<%= @comment.commenter(current_user) %>

如果您尝试设置@comment.commenter,则必须定义两个模型之间的关系。不确定您要完成什么,但可以在此处找到有关 Active Record 关联的更多信息:http://guides.rubyonrails.org/association_basics.html