Rails:添加问题以进行民意调查

时间:2014-01-27 20:05:42

标签: ruby-on-rails ruby-on-rails-4

在我的Rails应用程序中,我有投票和用户可以添加到民意调查的问题。我可以单独创建民意调查和问题,但如何将创建的问题添加到民意调查?

poll.rb

class Poll < ActiveRecord::Base

  has_many :questions

end

question.rb

class Question < ActiveRecord::Base

  belongs_to :poll

end

polls_controller.rb

class PollsController < ApplicationController

  def new
    @poll = Poll.new
  end

  def create
    @poll = Poll.create(poll_params)
    if @poll.save
      redirect_to poll_path(@poll)
      flash[:succsess] = "Poll created!"
    else
      render 'new'
    end
  end

    private

      def poll_params
        params.require(:poll).permit(:name)
      end

end

questions_controller.rb

class QuestionsController < ApplicationController

  def new
    @question = Question.new
    @poll = Poll.find(params[:id])
  end

  def create
    @question = Question.create(question_params)
    @poll.questions << @question
    if @question.save
      flash[:succsess] = "Question created"
    else
      render 'new'
    end
  end

  private

    def question_params
      params.require(:question).permit(:title, :comment)
    end

end

1 个答案:

答案 0 :(得分:1)

在您的民意调查模型中:

accepts_nested_attributes_for :questions

在你的HTML中:

<%= form_for @poll do |f| %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <%= f.fields_for :questions do |builder| %>
    <%= render "question_fields", :f => builder %>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>

在你的PollsController中:

def poll_params
  params.require(:poll).permit(:name, :question_fields => [:name, etc...])
end

看看:http://www.sitepoint.com/complex-rails-forms-with-nested-attributes/