我覺得你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 –