我正在尝试创建一个投票系统:
# models
class Poll < ActiveRecord::Base
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :poll
end
# routes
resources :polls do
resources :answers
end
Poll
具有一个字符串属性question
和Answer
,其中包含一个字符串属性answer
和一个整数votes
。
我希望这样,当用户创建Poll
时,会显示嵌套Answer
实例的表单。然后有一个带有AJAX调用的按钮用于另一个表单(最多可以说10个),因此可以添加多个答案。
我知道如何使用AJAX部分,但我不知道如何将子实例添加到尚不存在的父级。
我能想到的唯一方法是使用text_field_tag
将其传递给参数,然后在PollsController
create
方法中手动创建它。有点像这样:
def create
@poll = @poll.create(poll_params)
if @poll.save
if params[:poll_answer1].present?
@poll.answers.create!(answer: params[:poll_answer1])
end
if params[:poll_answer2].present?
@poll.answers.create!(answer: params[:poll_answer2])
end
flash[:notice] = "Poll created."
redirect_to @poll
else
flash[:error] = "Poll could not be created."
render :new
end
end
但似乎应该有更好的方法。我并不反对废弃整个设置,而是将问题放在Poll
的数组属性中。但是那里有计票的问题。