Rails 3: How to create a new nested resource?

后端 未结 3 823
日久生厌
日久生厌 2020-12-04 06:40

The Getting Started Rails Guide kind of glosses over this part since it doesn\'t implement the \"new\" action of the Comments controller. In my application, I have a book mo

3条回答
  •  情歌与酒
    2020-12-04 07:12

    Perhaps unrelated, but from this question's title you might arrive here looking for how to do something slightly different.

    Lets say you want to do Book.new(name: 'FooBar', author: 'SO') and you want to split some metadata into a separate model, called readable_config which is polymorphic and stores name and author for multiple models.

    How do you accept Book.new(name: 'FooBar', author: 'SO') to build the Book model and also the readable_config model (which I would, perhaps mistakenly, call a 'nested resource')

    This can be done as so:

    class Book < ActiveRecord::Base
      has_one :readable_config, dependent: :destroy, autosave: true, validate: true
      delegate: :name, :name=, :author, :author=, :to => :readable_config
    
      def readable_config
        super ? super : build_readable_config
      end
    end
    

提交回复
热议问题