2012-05-14 92 views
1

我對Rails很陌生,我正在編寫一個包含嵌套模型的註冊表單。提交表單時,用戶保存得很好,但嵌套模型不會將任何內容保存到預訂數據庫,並且控制檯不會引發錯誤。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 %> 
+0

您是否嘗試過在Rails控制檯中創建用戶? – Soliah

+0

Subscription類中的'new'和'create'方法是故意的? – moritz

+0

他們不是故意的,我加入的時候,當我「爲了這個絕望的狐狸,我會嘗試任何事情」模式。我編輯了帖子以刪除它們。 –

回答

0
+0

@Soliah我可以在Rails控制檯中創建用戶,但我不知道如何在User.new控制檯命令中包含嵌套屬性。 我試過使用 usernew = User.new(:name =>「Name」,:email =>「[email protected]」,:subscription_attributes => {:status =>「active」}) 但是它給我一個TypeError:不能將Symbol轉換爲Integer –

相關問題