Rails - 嵌套模型无法保存

时间:2012-05-14 05:35:58

标签: ruby-on-rails-3 nested-forms

我对Rails很新,我正在写一个包含嵌套模型的注册表单。当我提交表单时,用户保存得很好,但嵌套模型不会向Subscription数据库保存任何内容,并且控制台不会抛出任何错误。

我真诚地希望我不会错过一些非常明显的东西,我感谢您分享的任何提示。谢谢!

这是代码 -

型号:

class Plan < ActiveRecord::Base
  attr_accessible :posts, :name, :price
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :plan
  has_many :events
  has_one :subscription, :autosave => true

  accepts_nested_attributes_for :subscription

  attr_accessible :subscription_attributes

  def save_with_payment
    if valid?
    customer = Stripe::Customer.create(
      email:email, 
      plan: plan_id,
      card: stripe_card_token )
    self.stripe_customer_token = customer.id
    save!
  end
  rescue Stripe::InvalidRequestError => e
    logger.error "Stripe error while creating customer: #{e.message}"
    errors.add :base, "There was a problem with your credit card."
    false
  end
end

class Subscription < ActiveRecord::Base
  attr_accessible :plan_id, :status, :user_id
  belongs_to :user

end

这是用户控制器:

def new
  @user = User.new
  plan = Plan.find(params[:plan_id])
  @user = plan.user
  @user.build_subscription
end

def create
  @user = User.new(params[:user])
  if @user.save_with_payment
    sign_in @user
    flash[:success] = "Welcome to the SendEvent!"
    redirect_to @user
  else
    render 'new'
  end
end

这是表格:

<%= form_for @user, :html => {:class => "form-inline"} do |f|  %>
    <%= render 'shared/error_messages', object: f.object %>
    <div class="control-group">
      <%= f.label :name, :class => "control-label" %> 
      <%= f.text_field :name %>
    </div>  

    # A few more fields here and...

    # The nested model:
    <%= f.fields_for :subscription do |builder| %>
      <%= builder.hidden_field :status, :value => true %>
    <% end %>
    <%= f.submit "Create my account", class: "btn btn-large btn-primary", id: "submitacct" %>
<% end %>

1 个答案:

答案 0 :(得分:0)

来自RailsCasts

的示例应用

RailsCasts Episode #196: Nested Model Form (revised)

也许帮助你。