Question

I have models like this:

app/models/user.rb

class User < ActiveRecord::Base
    has_many :questions
    has_many :answers, :through => :questions
end

app/models/question.rb

class Question < ActiveRecord::Base   
has_many :answers   
has_many :users 
end

app/models/answer.rb

class Answer < ActiveRecord::Base
    belongs_to :user
    belongs_to :question 
attr_accessible :answer, :user_id, :question_id
end

And a registration form:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
                <div>Sign up</div>
                <div>

                  <div><p><%= f.label :email, "Email" %><%= f.email_field :email, :autofocus => true %></div>
                  <div><p><%= f.label :password, "Password" %></p><%= f.password_field :password %></div>
                  <div><p><%= f.label :password_confirmation , "Password" %></p><%= f.password_field :password_confirmation %></div>

                </div>
                <div>
                  <%= f.submit "Sign up" %></a></div>
                </div>
            <% end%>

Now i want to display my question field and answer field to this.

And the submitted answer has to be stored in "answers" table along with user_id and question_id.

How can I add answer field in the form?

Was it helpful?

Solution

You're getting down voted because SO is really for specific programming queries & questions (the more code the better), but here are some ideas for you:

According to Rails' ActiveRecord associations, you'd be best using the has_many :through association, effectively creating a join model; like this:

#app/models/question.rb
class Question < ActiveRecord::Base
    has_many :answers
    has_many :users, :through => :answers
end

#app/models/answer.rb
class Answer < ActiveRecord::Base
    belongs_to :user
    belongs_to :question
end

#app/models/user.rb
class User < ActiveRecord::Base
    has_many :answers
    has_many :questions, :through => :answers
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top