2013-09-21 5 views
4
내가 Belongs_to 연결을 공부하고

없이 작업을 Belongs_to 수, 나는 모든 주문 고객에 속한다는 점에서, 다음과 같은 모델을 사용하고, 그래서 만들 때 순서 모델에 순서이 has_many 또는 has_one

을 오류를 제공 belongs_to 사용했다 주문이 잘 작동 고객 모델에서, 그것은 만 belongs_to

작동하지 않는 이유 : #

  1. 내가 has_many를 사용 에 대한

    정의되지 않은 메서드 '주문'

  2. has_many를 사용한 작업 : 고객 모델의 주문은 이 아닙니다. has_one : 고객 컨트롤러에서 위와 동일한 오류가 발생합니다.

미리 감사드립니다.

모델 : - 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 

답변

10

기술적으로, belongs_to것이다 일 일치하지 않고 has_many 또는 has_one. 예를 들어 주문 belongs_to :customer이라고하면 Order 객체에 .customer을 호출하고 Customer 객체를 가져올 수 있습니다. .orders 고객이 has_many :orders (또는 .order,이 경우 has_one)의 코드를 사용하지 않고 has_many 선언으로 작성 되었기 때문에 고객에게 전화 할 수 없습니다.

그렇다고해서 관계의 절반 만 지정하고 싶지는 않을 것이라고 생각합니다. 그것은 끔찍한 디자인 선택이고, 당신은 그것을해서는 안됩니다.

편집 : has_onehas_many이 수행하는 .collection 메서드를 만들지 않습니다. the guide 당 :

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

당신에게 : 당신이 has_one 연결을 선언 할 때 has_one

에 의해 추가됨

4.2.1 방법의 선언 클래스 자동으로 협회에 관련된 네 가지 방법을 얻는다 해당 목록에 .new이 없음을 유의하십시오. 연결된 객체를 추가하려면 customer.build_order() 또는 customer.order = Order.new()을 사용할 수 있습니다.

+0

감사합니다. Belongs_to has_many에 대해서는 잘 작동하지만 belongs_to has_one의 경우 오류가 발생합니다. - 정의되지 않은 메소드'new '.. @order = @ customer.order.new (: order_date => params [: orderdate]); @ order.save; –