如何将父母与孩子联系起来?

时间:2015-12-10 18:30:24

标签: ruby-on-rails ruby ruby-on-rails-4

当我尝试为订单创建礼品卡时,该卡会被保存,但它永远不会链接到其父订单。 我看了很多资源,但没有一个能帮我理解原因。

这是我的Order.rb:

Order < ActiveRecord::Base
  has_many :order_items, dependent: :nullify
  attr_accessible :billing_address_id, :shipping_address_id, :shipping_address, :billing_address, :email, :shipping_address_attributes, :billing_address_attributes, :bill_to_shipping_address
  before_save :update_subtotal
  before_save :populate_guid
  belongs_to :user
  has_one :giftcard, dependent: :nullify
  belongs_to :billing_address, :class_name => "Address"
  belongs_to :shipping_address, :class_name => "Address"
  accepts_nested_attributes_for :shipping_address
  accepts_nested_attributes_for :billing_address, reject_if: :bill_to_shipping_address
  validates_uniqueness_of :guid

我的Giftcard.rb

class Giftcard < ActiveRecord::Base
  attr_accessible :from, :to, :message, :img1, :img2, :img3, :img4, :choose, :order_id
  belongs_to :order
end

路线:

resources :orders, only: [:new, :create, :update] do
    resources :giftcards, except: [:index, :show]
end

订单/ new.html.erb:

<%= link_to new_order_giftcard_path(@order), data: { modal: true } do %>
    go
<% end %> 

礼品卡/ new.html.erb

<%= form_for [@order, @giftcard], remote: request.xhr?, html: { data: { modal: true } } do |f| %> 
  From<%= f.text_field :from, placeholder: "Martin" %>
  To<%= f.text_field :to, placeholder: "Jeanne" %>
  <%= f.text_area :message, placeholder: "Thanks" %>
  <%= f.submit "go" %>
<% end %>

最后是我的giftcards_controller.rb:

class GiftcardsController < ApplicationController
respond_to :html, :json
layout false, :only => [:edit, :new, :show]
before_action :set_giftcard, :only => [:create, :update]

def new
    @order = Order.find(params[:order_id])
    @giftcard = Giftcard.new
end 

def create 
    @order = Order.find(params[:order_id])
    @giftcard = Giftcard.new(gift_card_params)
    if @giftcard.save 
       @order.update(params[:order])
       @giftcard.update_attribute(:choose, true)
       respond_modal_with @order, location: new_order_path
    end
end 
private

def gift_card_params
    params.require(:giftcard).permit(:from, :to, :message, :img1, :img2, :img3, :img4, :order_id)
end 

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在控制器

.on('click', function()