我觉得你participant
和user
模型需要被合并成一个,因为不是participant
的user
?我不明白为什么Participant
模型在这里是必要的。
说,我们合并User
和Participant
逼到User
,User
和Voting
之间的关联将被:
User < ActiveRecord::Base
has_and_belongs_to_many :surveys
has_many :votings
end
Voting < ActiveRecord::Base
belongs_to :answer
belongs_to :user
attr_accessible :value
end
从你的第一个代码块
现在:
Question 1
- Answer1 -> Please vote -1/0/1 (Checkbox field)
- Answer2 -> Please vote -1/0/1 (Checkbox field)
- Answer3 -> Please vote -1/0/1 (Checkbox field)
- Participant Comment (Text Field)
- Participant Average (Rating Field)
是不是投票用户的答案完成?那么我们是否需要user has_many :votings
关系?我认为协会口语会是User
需要很多Surveys
,Survey
有很多Questions
,Question
有很多Answers
和答案有很多Votings
。每个投票都可以被检查。所以对于这个我不认为User
和Voting
之间的直接联系是解决方案。
以下是更新User
,Answer
和Voting
机型更新的关联:
User < ActiveRecord::Base
has_and_belongs_to_many :surveys
end
Answer < ActiveRecord::Base
belongs_to :question
has_many :votings
end
Voting < ActiveRecord::Base
belongs_to :answer
attr_accessible :value
end
最后有一对夫妇的其他小错别字像Answers < ActiveRecord::Base
其中类Answer
不应该是复数。
第二个问题是你有User
has_and_belongs_to_many
Surveys
。要定义many to many
关系Survey
之间User
,所以你需要定义同在Survey
型号还有:
Survey < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :questions
end
与所有这些更新与关系沿着您的模型将如下所示(注:我也在模型中加入accepts_nested_attributes_for
所以,当你的表单提交你不需要手工打造每一个相关联的对象):
User < ActiveRecord::Base
has_and_belongs_to_many :surveys
end
Survey < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :questions
accepts_nested_attributes_for :questions
end
Question < ActiveRecord::Base
belongs_to :survey
has_many :answers
accepts_nested_attributes_for :answers
end
Answers < ActiveRecord::Base
belongs_to :question
has_many :votings
accepts_nested_attributes_for :votings
end
Voting < ActiveRecord::Base
belongs_to :answer
attr_accessible :value
end
使用上述模型relationshp你可以建立你的SurveysController
的new
和create
行动将类似于如下:
# app/controllers/surveys_controller.rb
class SurveysController < ApplicationController
def new
@survey = current_user.surveys.build do
@question = @survey.questions.build
@answer = @question.answers.build
# Build three different votings for answer with default value.
[-1, 0, 1].each do |voting_value|
@answer.votings.build(value: voting_value)
end
end
def create
@survey = current_user.surveys.build(params[:survey])
@survey.save
# Of course you would check if save succeeded or failed and take action accordingly.
end
end
此外,我建议你看看has_many...through
而不是has_and_belongs_to_many
定义many to many
关系。
请张贴您的模型与关系定义。 – vee
这个人的模型可能会给你的一些亮光http://stackoverflow.com/questions/20612855/redirecting-to-new-page-with-already-existing-records-after-user-login-for-authe –