Reputation: 5009
I have a form attached to profiles where short comments can be submitted. I want to capture the author's name though so I can display it in a tooltip when hovering over the comment's body.
In my create
method in the controller I have:
def create
@comment = Comment.new(params[:comment])
@comment.save!
redirect_to profile_path(@comment.profile)
end
Inside my migration:
t.timestamps
t.integer :profile_id
t.string :author_id
t.string :body
Profile model:
belongs_to :user
accepts_nested_attributes_for :user
has_many :comments
Comment model:
belongs_to :profile
ProfilesController:
def show
@user = User.find(params[:id])
@profile = user.profile
@superlative = @profile.superlatives.new
end
And my form:
<%= form_for @comment do |f| %>
<%= f.hidden_field :profile_id, :value => @profile.id %>
<%= f.hidden_field :author_id, :value => "#{current_user.profile.first_name} #{current_user.profile.last_name}" %>
<%= f.text_field :body %>
<%= f.submit 'Add new' %>
<% end %>
I was thinking of linking the :author_id to current_user.profile.id and using that association to display :first_name and :last_name which are attributes of the profile. Or is there a simpler, better way?
UPDATE: I got it to display the name though I'm still curious if there's a better way.
Upvotes: 0
Views: 544
Reputation: 1430
I would suggest something like this:
In your routes.rb
create a nested resource for comments
resources :users do
resources :comments
end
In your User
model
class User
has_many :comments
end
In your Comment
model
class Comment
belongs_to :user
end
In your CommentsController
in the new
and create
methods
@comment = User.find(params[:user_id]).comments.new(params[:comment])
So the comment automagically gets created as belonging to that User and you don't have to pass anything around.
Then, in your Comment view, you could just call its owners name
@comment.user.first_name
Upvotes: 1
Reputation: 13675
Your solution looks fine, but I'd store the User
(or whatever class current_user
returns) instead of the Profile
:
In app/models/comment.rb
:
class Comment < ActiveRecord::Base
belongs_to :profile
belongs_to :author, :class_name => "User", :foreign_key => "author_id"
... rest of the code ...
end
You then change your migration to:
t.integer :author_id
and your controller method to:
def create
@comment = Comment.new(params[:comment].merge(:author_id => current_user.id))
@comment.save!
redirect_to profile_path(@comment.profile)
end
In your view (I used the title
attribute do create a tooltip, but feel free to use whatever method you like):
<div class="comment" title="<%= @comment.author.profile.first_name %> <%= @comment.author.profile.last_name %>">
<%= @comment.body %>
</div>
Upvotes: 1