Reputation: 10380
Workaround for the below:
<%= f.label :Commenter %><br>
<%= f.text_field :commenter, :value => current_user.name %>
This works for passing the username to the commenter attribute without having to type it in - with the addded bonus of being able to edit it if necessary!
I am trying to make my website show the name of the user who created a comment. In order to do this, I would like the commenter (attribute of comment) to be assigned as current_user.name.
comment has attributes commenter, body, and expdate.
Is it possible to pass current_user.name to the comment.create method through the form?
I've tried this:
<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>
Where I assigned the commenter attribute to be current_user. Does this not pass that to the create method?
I have also tried assigning it in the comments_controller like this:
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
But I get an error complaining that commenter is not a defined method.
Both of the methods I tried don't allow me to create a comment, does anyone have any ideas of how I might do this? Many thanks in advance!
Upvotes: 1
Views: 138
Reputation: 1089
In the controller, like this:
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
And in the view:
<% @project.comments.each do |comment| %>
<tr>
<td><%= comment.body %></td>
<td><%= comment.commenter %></td>
</td>
</tr>
<% end %>
Upvotes: 1
Reputation: 6942
You can do this in the create method in your controller:
@commenter = current_user.name
It's that simple. And if you need to access the commenter name in your view, add this to your comment class:
def commenter(user)
user.name
end
Then in your view:
<%= @comment.commenter(current_user) %>
If you're trying to set @comment.commenter, you will have to define the relation between the two models. Not sure exactly what you're trying to accomplish, but more info about Active Record associations can be found here: http://guides.rubyonrails.org/association_basics.html
Upvotes: 2