开发者

Rails 3 - Nested Forms, how to count nested resources

Hi, I'm a Rails newbie and this is my first stackoverflow question.

I'm currently writing a poll application, the concept is very simple.

The User can create a new poll by giving it a title and some possible answers.

The answers can be added or removed by using javascript:void(0) links (see picture)

Everything works great so far (thanks to ryanb's nested_form gem), but now I'm asking myself how can I count the number of the given answers, so I can limit it to say at most 5 answers per question?

(currently you can create an unlimited number of answers)

The answer creating part of the poll form looks like - THIS - in the browser.

Poll-Model (poll.rb):

class Poll < ActiveRecord::Base
  has_many :answers,  :dependent => :destroy
  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end

Answer-Model (answer.rb):

class Answer < ActiveRecord::Base
  belongs_to :poll
  validates_presence_of :name
end

My开发者_StackOverflow current approach of counting the answers (polls_controller.rb):

def new
  @poll = Poll.new
  2.times { @poll.answers.build }
end


def create  
  ...

  if @poll.answers.count > 10
    flash[:alert] = 'Too many answers (not exceeding 10), please remove some'
    render :action => 'new'
    return
  end

  if @poll.save
    redirect_to poll_path(category_slug(@poll), @poll.id), :notice => 'Successfully created poll.'
  else
    render :action => 'new'
  end

  ...
end

Obviously my method won't work, because the answers aren't created yet, so my question is:

  • How and where (JavaScript, Polls-Controller, Poll-Model) should I count the number of the given answers, so I can limit the number

Thanks, I really appreciate every answer.


Does :limit as part of nested_attributes work?

e.g.

accepts_nested_attributes_for :answers, :limit => 5, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜