我有一項調查,並且我希望在第一次用戶回答問題時將參與者添加到Participant
模型。這項調查有點特別,因爲它有很多功能來回答標記詞,多項選擇和開放問題等問題,而且每個功能實際上都是一個擁有自己記錄的模型。另外我只希望參與者保存一次。在創建時向模型中添加記錄在許多模型中使用
的參與模式相當簡單:
class Participant < ActiveRecord::Base
belongs_to :survey
attr_accessible :survey_id, :user_id
end
調查模式也很簡單:
class Survey < ActiveRecord::Base
...
has_many :participants, :through => :users
has_many :rating_questions, :dependent => :destroy
has_many :open_questions, :dependent => :destroy
has_many :tag_questions, :dependent => :destroy
belongs_to :account
belongs_to :user
accepts_nested_attributes_for :open_questions
accepts_nested_attributes_for :rating_questions
accepts_nested_attributes_for :tag_questions
...
end
然後,你必須等車型rating_answers
屬於一個3210,open_answers
屬於open_questions
等等。
所以起初我還以爲我的模型中rating_answers
我可以添加after_create
回調add_participant
這樣的:
class RatingAnswer < ActiveRecord::Base
belongs_to :rating_question
after_create :add_participant
...
protected
def add_participant
@participant = Participant.where(:user_id => current_user.id, :survey_id => Survey.find(params[:survey_id]))
if @participant.nil?
Participant.create!(:user_id => current_user.id, :survey_id => Survey.find(params[:survey_id]))
end
end
end
在這種情況下,我不知道如何找到survey_id,所以我嘗試使用params,但我不認爲這是正確的做法。 regardles它返回此錯誤
NameError (undefined local variable or method `current_user' for #<RatingAnswer:0x0000010325ef00>):
app/models/rating_answer.rb:25:in `add_participant'
app/controllers/rating_answers_controller.rb:12:in `create'
另一個想法我已經是創造,而不是一個模塊Participants.rb
,我可以在每個控制器
module Participants
def add_participant
@participant = Participant.where(:user_id => current_user.id, :survey_id => Survey.find(params[:survey_id]))
if @participant.nil?
Participant.create!(:user_id => current_user.id, :survey_id => Survey.find(params[:survey_id]))
end
end
end
,並在控制器
class RatingAnswersController < ApplicationController
include Participants
def create
@rating_question = RatingQuestion.find_by_id(params[:rating_question_id])
@rating_answer = RatingAnswer.new(params[:rating_answer])
@survey = Survey.find(params[:survey_id])
if @rating_answer.save
add_participant
respond_to do |format|
format.js
end
end
end
end
,而且我用出現路由錯誤
ActionController::RoutingError (uninitialized constant RatingAnswersController::Participants):
我可以理解這個錯誤,因爲我沒有用於創建方法及其路由資源的參與者的控制器
我不確定從嵌套添加記錄到模型的正確方法是什麼模型和更清潔的方法是什麼。
想法是最受歡迎的!
current_user是一個可以在視圖/控制器中單獨訪問的助手。您需要將其作爲參數傳遞給模型。否則,它不能在模型中訪問。 –
我也看到您在創建評分答案對象時沒有傳遞任何評分問題數據。 –
謝謝,您指出了一個可能的解決方案。我會在下面發表我的回答。 –