Hi,
I’ve been playing with Rails for a few months now and I enjoying it. But
most recently, I’ve just come across an issue that I just can’t seem to
resolve, to the point where I’ve recreated a small application from
scratch to reproduce the issue (and I’m confident the problem is with me
not knowing the language well enough).
Here’s the issue…
I have ACCOUNTS that hold zero or more OPERATIONS. Each OPERATION has a
FROM ACCOUNT and a TO ACCOUNT (think accounting). See below for some
schema information.
Here’s the code for the account.rb model:
class Account < ActiveRecord::Base
has_many :operations, :order => “actual_date”
def has_operations?
#
# The problem is the “???” what do I replace them with?
# :id doesn’t work
# @id doesn’t work wither
# self.id doesn’t work
#
if ( Operation.find_by_from_account_id( ??? ).size > 0 ||
Operation.find_by_to_account_id( ??? ).size > 0 )
return true
else
return false
end
end
end
And here’s my show.rhtml
<% for column in Account.content_columns %>
<%= column.human_name %>: <%=h @account.send(column.name) %>
<% end %><% if @account.has_operations? %>
Operations
<%= operation.actual_date %> | <% end %><%= link_to 'Show', :action => 'show', :id => operation %> | <%= link_to 'Edit', :action => 'edit', :id => operation %> | <%= link_to 'Destroy', { :action => 'destroy', :id => operation }, :confirm => 'Are you sure?', :method => :post %> |
Now the above works if I remove the “has_operations?” method from my
“account.rb” file AND my Operations table looks like this:
create_table “operations”, :force => true do |t|
t.column “actual_date”, :datetime
t.column “amount”, :decimal
t.column “account_id”, :integer
t.column “to_recipient”, :string
end
*Notice the “account_id” instead of “to_account_id” and
“from_account_id”.
As Rails is nice enough to understand the “has_many” and “belongs_to”
relationships. But when I change “account_id” to “from_account_id” and
“to_account_id”;
create_table “operations”, :force => true do |t|
t.column “actual_date”, :datetime
t.column “amount”, :decimal
t.column “from_account_id”, :integer
t.column “to_account_id”, :integer
end
the dynamically generated “has_operations?” method shits to bed as it
cannot find “account_id” (makes sense). So I replace it (maybe there’s
another way) with the version shown above. This new method gets called
directly from the “show.rhtml” file and all I need from the instance is
the “id” – which Rails discovers and uses in it’s own “has_operations?”
method when it generates it, but I can’t seem to get to with my
version…
Your help would be much appreciated!
Thanks!
Marc :o)