在Rails中创建具有has_one关联的2个对象

我需要获得一些有关在Rails中通过validation创建新对象的信息。 例如,有以下代码:

def create @user = User.new(params[:user]) if @user.save # some actions: redirect, render, etc else render 'new' end end 

但是如果有2个模型与has_one关联,例如Club和Place。 我需要在同一个’创建’动作中从params创建这两个对象,因为我有相同的forms为它输入数据( params[:club]params[:club][:place] )。 我不知道如何保存这些物品,因为建造一个地方( @club.build_place(params[:club][:place]) )我应该将@club保存在数据库中。 请给我举例说明我的问题代码。 提前致谢。

如果你从一个表单创建多个对象,你可能最好把这个逻辑放到一个“表单对象”中……从这里找到的CodeClimate博客中查看文章“7个重构Fat ActiveRecord模型的模式”(看看有关提取表单对象的第3节): http : //blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models 。

Railscasts在表单对象上也有很好的一集,虽然它是一个“专业剧集”(即需要订阅)。 http://railscasts.com/episodes/416-form-objects

简而言之,您创建一个自定义模型,包括一些必要的ActiveModel模块,然后创建一个自定义保存方法,例如(这直接来自有很多很好建议的文章)。

 class Signup include Virtus extend ActiveModel::Naming include ActiveModel::Conversion include ActiveModel::Validations attr_reader :user attr_reader :company attribute :name, String attribute :company_name, String attribute :email, String validates :email, presence: true # … more validations … # Forms are never themselves persisted def persisted? false end def save if valid? persist! true else false end end private def persist! @company = Company.create!(name: company_name) @user = @company.users.create!(name: name, email: email) end end 

这为您提供了更多控制和更清晰的界面。