Reputation: 87
I am building a question/answer app. The questions are static and provided, not user generated. The data is being accessed via a nested relationship.
On the individual user view I want to show a list of the questions that the user has answer and its associated answer. Like this:
Question 1 User 1 answer
At this point, I am showing each question, but all of the answers are showing, not just those of the specific user. Like this:
Question 1 User 1 answer User 2 answer
Here is the code in my show.view. I have also tried it without the "if answer.user" line and got the same result.
<% @user.questions.uniq.each do |question| %>
<h3><div class="answer"><%= question.question %> </div></h3>
<% question.answers.each do |answer| %>
<% if answer.user = current_user %>
<div class="answer"><%= answer.answer %> <%= answer.created_at.strftime("(%Y)") %></div>
<% end %>
<% end %>
<% end %>
My models:
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
end
class Question < ActiveRecord::Base
has_many :answers
has_many :users, through: :answers
end
class User < ActiveRecord::Base
has_many :answers
has_many :questions, through: :answers
end
My Routes:
resources :users do
resources :answers
end
I'm happy to provide any other code that would be helpful. Thanks!
Upvotes: 0
Views: 49
Reputation: 42919
Actually i prefer to treat it on a different level, I believe this should work too
<% @user.questions.uniq.each do |question| %>
<h3><div class="answer"><%= question.question %> </div></h3>
<% question.answers.where(user: @user).each do |answer| %>
<div class="answer"><%= answer.answer %> <%= answer.created_at.strftime("(%Y)") %></div>
<% end %>
<% end %>
Upvotes: 1
Reputation: 249
You assign current_user to answer.user, you want test equality change with this line
if answer.user == current_user
Upvotes: 1