我对 Rails 很陌生,我正在编写一个包含嵌套模型的注册表单。当我提交表单时,用户保存得很好,但嵌套模型不会将任何内容保存到订阅数据库,控制台也不会抛出任何错误。
我真诚地希望我没有遗漏一些非常明显的东西,我很感激你可以分享的任何提示。谢谢!
这是代码-
楷模:
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 %>