Rails中的关系

时间:2013-12-11 10:18:13

标签: ruby-on-rails relationships

我有这样的模特:

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

注册表格:

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

现在我想显示我的问题字段和答案字段。

提交的答案必须与user_idquestion_id一起存储在“答案”表中。

如何在表单中添加答案字段?

1 个答案:

答案 0 :(得分:0)

你正在投票,因为SO真的是针对特定的编程查询&amp;问题(代码越多越好),但这里有一些想法:

根据Rails' ActiveRecord associations,您最好使用has_many :through关联,有效地创建连接模型;像这样:

#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