can Belongs_to work without has_many or has_one
Asked Answered
L

1

8

I am studying Belongs_to association, I have used following models, in that every order belongs to the customer, so I have used belongs_to in order model it giving error while creating order

undefined method `orders' for #

  1. when I use has_many :orders in customer model it works fine, why it does not work with only belongs_to

  2. Its work with has_many :orders in customer model but not with has_one : order in customer controller it giving same above error.

thanks in advance.

Model :- order.rb

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

Model :- customer.rb

class Customer < ActiveRecord::Base
  attr_accessible :name
end

controller :- 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
Lacewing answered 21/9, 2013 at 14:51 Comment(0)
B
17

Technically, belongs_to will work without a matching has_many or has_one. If, for instance, you say that Order belongs_to :customer, you can call .customer on an Order object, and get a Customer object. What you can't do is call .orders on a Customer without telling it that it has_many :orders (or .order, in the case of has_one), because that method is created by the has_many declaration.

That said, I can't think of any reason you would ever want to only specify half of a relation. It's a terrible design choice, and you should not do it.

Edit: has_one doesn't create the .collection methods that has_many does. Per the guide:

4.2.1 Methods Added by has_one

When you declare a has_one association, the declaring class automatically gains four methods related to the association:

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

You'll note that there's no .new on that list. If you want to add an associated object, you can use customer.build_order(), or customer.order = Order.new().

Bifurcate answered 23/9, 2013 at 1:34 Comment(1)
okay thanks. Its work fine for Belongs_to has_many, but in case of belongs_to has_one it gives error :- undefined method `new'.. @order = @customer.order.new(:order_date => params[:orderdate] ); @order.save;Lacewing

© 2022 - 2024 — McMap. All rights reserved.