Junk loading does not work in Rails 2.2.2

I am working with models similar to the following:

class Owner < ActiveRecord::Base
  has_many :owned
end

class Owned < ActiveRecord::Base
  belongs_to :owner
end

      

You can assume the property_id and owner_id are in the right places. The problem is in the controller for another mvc network in the application

@owner = Owned.find_by_id(owned_id, :include => :owner)

      

does not work. Naturally i get owner_id, column but cant do

@owned.owner # is just nil

      

What gives? What I mean is that I could do the assignment just before passing the result to the view:

@owned.owner = Owner.find_by_id(@owned.owner_id)

      

but that just seems silly. Come on, embarrass me. What's the obvious thing that I missed? This works elsewhere in my application, but I can't see the difference. Are there common pitfalls? Anything helps.

thanks

0


a source to share


2 answers


I just keep winning. The corresponding Owner object has been removed from the owners table.



The funny thing is, before I created the account, I had a ton of karma on my cookie based identity. Then my cookies got messed up and I can no longer ask anything but stupid questions and my karma is sitting at 1. Oh good.

+1


a source


The reputation on StackOverflow is not cookie-based. You may need to login again or something.

Your question seems to imply that you have an own_id field in the owner table. You don't need this and need to remove it.

You only need an integer owner_id in the table it owns.

You can access your records and relationships in several ways. First, start by accessing the owner record first.

owner = Owner.find(owner_id)
owned = owner.owned # this is an array since you a 'has_many' relationship

      

Typically, you want to access existing records like this:



for owned in owner.owned
 puts owned.name # or access any other attributes
end

      

If you want to access the registered records first, you can do the following:

@owned = Owned.find(:all, :conditions => [ "owner_id = ?", owner_id ])
# @owned is an array so you need to iterate through it
for owned in @owned
  puts owned.owner.name # or access any other attribute from the owner
end

      

Once your queries are working fine, you can worry about the loading load by adding: include to your search statements. Note that this may be of interest for optimization, but not necessarily from get go.

Hope this helps.

+1


a source







All Articles