我是rails的新手,需要一些指导。我确信我误解了一些明显的东西。
我想要留下评论的人的用户名显示在视图页面上。我有一部分内容通过特定对象的评论集合,例如学校。我无法弄清楚如何将该用户变量传递给partial,以便我可以显示注释的登录名。我的评论模型是多态的,我很确定这会让这更复杂。
以下是模型:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
has_many :comments, :through => :schools
class School < ActiveRecord::Base
belongs_to :installation
belongs_to :neighborhood
has_many :comments, :as => :commentable
class User < ActiveRecord::Base
has_many :users, :through => :schools
学校的管理员:
def show
@installation = Installation.find(params[:installation_id])
@school = School.find(params[:id])
@neighborhood = @school.neighborhood
@comment = @school.comments
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @school }
end
end
评论部分:
<div class="box-one">
<img src="/images/comment_top.png" alt="" />
<div class="inside">
<p><span class="stars"><%= display_stars(comment.stars) %></span><br />
<%= comment.content %></p>
</div>
<img src="/images/comment_bottom.png" alt="" />
</div>
学校观点:
<%= render :partial => "shared/comment", :collection => @comment %>
答案 0 :(得分:2)
我认为您的模型可能存在一些问题,但您使用locals
将参数传递给部分。
<%= render :partial => "shared/comment", :locals => { :user => your_user } %>
然后在部分内部,您可以访问用户变量。
<p><span class="stars"><%= display_stars(comment.stars) %></span><br />
<%= comment.content %><br />
by <%= user %></p>
答案 1 :(得分:0)
例如来自我
def show
@school = School.find_by_id_and_user_id(params[:id],
params[:user_id],:include => [:user, [:comments => :user]])
end
class Comment < ActiveRecord::Base
belongs_to :school, :counter_cache => true
belongs_to :user
end
class School < ActiveRecord::Base
belongs_to :user, :counter_cache => true
has_many :comments
def after_save
self.user.update_attribute(:last_activity, "bla bla bla")
self.user.update_attribute(:last_activity_at, Time.now)
end
end
class User
has_many :school or has_one
has_many :comments
end
<div class="box-one">
<img src="/images/comment_top.png" alt="" />
<div class="inside">
<% @schools.comments.each do |comment| -%>
<%= comment.created_at.to_s(:short) %>
<p><span class="stars"><%= <%= comment.user.stars %> said: ## or<%= comment.user.username %> said:##</p> %></span><br />
<%= comment.content %></p>
</div>
<img src="/images/comment_bottom.png" alt="" />
</div>
<%= render :partial => "shared/comment"%>