Rails assignment table with third column
I currently have a model for an 开发者_如何学编程assignment table in Rails 3, which looks as follows (there are, of course, sale and financeCompany models also):
class SaleFinanceCompany < ActiveRecord::Base
attr_accessible :sale_id, :financeCompany_id, :financedBalance
belongs_to :sale
belongs_to :financeCompany
end
My question is simple: how can I set up the sale/financeCompany models so that I can access the associated financedBalance?
For example, in my view I would like to have:
<% for financeCo in sale.financeCompanies %>
<%= "£" + financeCo.financedBalance + " from "%>
<%= financeCo.name %>
<% end %>
That unfortunately does not work, with the error being the financedBalance part. The only way I could see to set up my finance company model would be with a
has_many :financedBalances, :through => :saleFinanceCompanies
but this will give me several financedBalances for each sale, but I need one (each financedBalance is tied to both a sale and finance company in the assignment table, so doing sale.financedBalances.where etc.
would seem unnecessary when I should be able to do sale.financeCompany.financedBalance
).
Any suggestions?
Rails treats join tables a bit differently than you might think. From a DBA perspective, your join table is perfectly fine but for Rails true join tables have only referential columns. As soon as you add a new column, Rails likes to treat the join table as a new entity.
(On a personal note, I was frustrated by this at first but I quickly learned it's not a big deal)
So, to fix your problem, you'll need to rename your table, let's say FinanceBalances. Also, let's change financedBalance to amount.
Then, in your Sale.rb file put you associations like so:
has_many :financeBalances
has_many :financeCompanies, :through => :financeBalances
Do the same for FinanceCompany.
And your code will look like:
<% for financeBalance in sale.financeBalances %>
<%= "£" + financeBalance.amount + " from " %>
<%= financeBalance.financeCompany.name %>
<% end %>
If you really really want financeCompany.financedBalance
to work, you can define a method in your financeCompany model and write the query that returns what you want.
精彩评论