Can Belongs_to work without has_many or has_one

I am studying the Belongs_to association, I used the following models, since each order belongs to the client, so I used property_to in the model model, which gave an error when creating the order

undefined method `orders' for #

  • when I use has_many: orders in the client model work fine, why does not work with only_to

  • His work with has_many: orders in the client model, but not with has_one: order in the client controller, which gives the same error above.

early.

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 

: - 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 
+4
source share
1 answer

Technically, belongs_to will work without matching has_many or has_one . If, for example, you say that Order belongs_to :customer , you can call .customer on the Order object and get the Customer object. What you cannot do is call .orders on the Client without telling him that he has_many :orders (or .order , in the case of has_one ), because this method is created by the has_many declaration.

However, I cannot think of any reason why you would only like to indicate half the relationship. This is a terrible design choice, and you should not do that.

Edit: has_one does not create .collection methods that has_many does. Per manual :

4.2.1 Methods added by has_one

When you declare a has_one association, the declaration class automatically receives four methods associated with the association:

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

You will notice that there is no .new on this list. If you want to add a related object, you can use customer.build_order() or customer.order = Order.new() .

+11
source