0
votes

Currently stuck on a problem

I have a company.rb model that has_many :applications

The application.rb model belongs_to :company and has_many :answers

The answer.rb model belongs_to :application.rb and has_many :users

The user.rb model has_many :answers

I allow a company to create an application. There they can input questions. The user can view them and their answers will be stored in answer.rb.

What I'm trying to do now is display all current_company.applications that have received an answer.

I tried this:

<% @applications.all.each do |f| %>

<%= f.answers.answer_1 %><br>

<% end %>

whilst having my controller:

 def applicants
   @applications = current_company.applications
 end

however I get undefined method `answer_1'. It doesn't seem I'm available to access it. I store it like this: the applications has a company_id and the answers has an application_id and a user_id.

I thought that by doing i the way I do now I'm able to access all applications created by the current company. From there I can view all application_id in the answers as those are the one's I'm outputting but it's not working.

1
What is answer_1? and what do u intend to print out? - Acacia
How do you represent the question? Also, how comes that an answer has_many :users? - Tamer Shlash
@Acacia I let the company input 3 questions. Stored question_1, question_2, question_3. I then have a model called answers that store answer_1, answer_2, answer_3 - user2755537
@TamerShlash because several users can answer the same question, and one user can answer several other questions that belongs to different applications_ids. Is that wrongly configured? - user2755537
@user2755537 are question_1, question_2, question_3 and answer_1, answer_2, answer_3 all fields in the Answer.rb model? - Tamer Shlash

1 Answers

0
votes

I think you understood the way you can access nested models wrongly.

When an application has_many: :answers, then @application.answers is a collection you can iterate through. For example (in your view):

<% @applications.each do |application| %>
  <% application.answers.each do |answer| %>
     <%= answer.text %>
  <% end %>
<% end %>

(assuming that your answer model has a text attribute).