0

I am new to rails and need some guidance. I am sure I am misunderstanding something obvious.

I would like the user name of the person who leaves a comment to show on the view page. I have a partial that goes through the collection of comments for the particular object for example a school. I can't figure out how to pass that user variable into the partial so that I can display the login name for the comment. My Comments model is polymorphic and I am pretty sure that is making this more complex.

Here are the models:

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

School's controller:

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

The comment partial:

<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>

The school view:

<%= render :partial => "shared/comment", :collection => @comment %>
4

2 に答える 2

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>
于 2009-08-18T05:31:25.270 に答える
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"%>
于 2009-08-18T06:31:01.967 に答える