2014-01-27 26 views
0

在我的Rails應用程序中,我有用戶可以添加到投票的投票和問題。我可以分別創建民意調查和問題,但是如何將創建的問題添加到民意調查?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 
+2

的http:// railscasts。 COM /次/ 196-嵌套模型外形部分-1 –

回答

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/