Belongs_to可以在没有has_many或has_one的情况下工作

时间:2013-09-21 14:51:33

标签: ruby-on-rails-3 associations belongs-to

我正在研究Belongs_to协会,我使用了以下模型,因为每个订单都属于客户,所以我使用了belongs_to,以便在创建订单时给出错误

  

未定义的方法`命令'对于#

  1. 当我在客户模型中使用has_many:orders时,它运行正常,为什么呢 不适用于belongs_to

  2. 与has_many合作:客户模型中的订单,但没有 has_one:客户控制器中的订单,它给出了相同的错误。

  3. 提前感谢。

    型号: - order.rb

    class Order < ActiveRecord::Base
      belongs_to :customer
      attr_accessible :order_date, :customer_id
    end
    

    型号: - customer.rb

    class Customer < ActiveRecord::Base
      attr_accessible :name
    end
    

    控制器: - orders.rb

      def create
         @customer = Customer.find_by_name(params[:name])
        @order = @customer.orders.new(:order_date => params[:orderdate] )
    
        respond_to do |format|
          if @order.save
            format.html { redirect_to @order, notice: 'Order was successfully created.' }
            format.json { render json: @order, status: :created, location: @order }
          else
            format.html { render action: "new" }
            format.json { render json: @order.errors, status: :unprocessable_entity }
          end
        end
      end
    

1 个答案:

答案 0 :(得分:11)

从技术上讲,belongs_to 无法匹配has_manyhas_one。例如,如果您说订单belongs_to :customer,则可以在Order对象上调用.customer,并获取Customer对象。 你不能做的就是给客户打电话.orders而不告诉客户has_many :orders(或.orderhas_one),因为该方法已创建通过has_many声明。

那就是说,我想不出你想要只指定一半关系的任何理由。这是一个糟糕的设计选择,你不应该这样做。

修改:has_one不会创建.collection所做的has_many方法。每the guide

  

4.2.1 has_one

添加的方法      

声明has_one关联时,声明类   自动获得与关联相关的四种方法:

association(force_reload = false) 
association=(associate)
build_association(attributes = {}) 
create_association(attributes = {})

您会注意到该列表中没有.new。如果要添加关联对象,可以使用customer.build_order()customer.order = Order.new()

相关问题