这是我的模型和关联:
项目
class Project < ActiveRecord::Base
...
has_many :projectmemberizations
has_many :users, :through => :projectmemberizations
has_many :project_comments
...
end
项目评论
class ProjectComment < ActiveRecord::Base
attr_accessible :comment, :created_at, :project_id, :user_id, :user_name
belongs_to :project
has_many :projectcommentations
has_many :users, :through => :projectcommentations
def user
self.user
end
end
项目评论
class Projectcommentation < ActiveRecord::Base
attr_accessible :comment_id, :project_id, :user_id, :user_name
belongs_to :project_comment
belongs_to :user
end
用户
class User < ActiveRecord::Base
belongs_to :account
has_many :projectmemberizations
has_many :projects, :through => :projectmemberizations
has_many :projectcommentations
has_many :project_comments, :through => :projectcommentations
end
问题
如您所见,用户可以对项目发表评论。这工作正常。但我试图开始工作的是在 WHO 创建评论的视图中显示。现在我正在尝试这样做,它没有产生任何错误,但只是没有为 user_name 显示任何内容。
<% @project.project_comments.each do |comment|%>
<div class="comment">
<%= image_tag current_user.photo.url(:small) %>
<strong><%= comment.user_name %></strong>
<%= comment.comment %>
</div>
<% end %>
最后,如果我这样做,我可以在 Rails 控制台中使用它:
comment = ProjectComment.first
comment.user_id = 1
comment.save
comment.user.name
那么显然添加评论时它没有保存user_id?顺便说一下,很抱歉这篇文章的长度!
PS这里是她的节目和project_comments控制器中的新动作:
def show
@project_comment = ProjectComment.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @project_comment }
end
end
def new
@project_comment = ProjectComment.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @project_comment }
end
end
ProjectComment 创建方法
def create
@project_comment = ProjectComment.new(params[:project_comment])
respond_to do |format|
if @project_comment.save
format.html { redirect_to project_url(@project_comment.project_id), :notice => 'Project comment was successfully created.' }
format.json { render :json => @project_comment, :status => :created, :location => @project_comment }
else
format.html { render :action => "new" }
format.json { render :json => @project_comment.errors, :status => :unprocessable_entity }
end
end
end
来自创建评论的视图中的代码
<%= form_for(@project_comment) do |f| %>
<%= f.hidden_field :project_id, :value => @project.id %>
<%= image_tag current_user.photo.url(:small) %>
<%= f.text_area :comment, :class => "addcomment" %>
<%= f.submit :value => "Comment", :class => "tagbtn" %>
<% end %>