0

I am building an Web app using Rails 3.2. I have three tables. Item, Task and Articles.

TASK

has_many :articles
has_many :items, :through => :articles

ITEM

has_many :articles
has_many :tasks, :through => :articles

ARTICLE

belongs_to :task
belongs_to :item

In the join table (Article) I got an extra field called amount. How can I set this field when creating the relationship?

Right now I do it like this but it does not feel "right".

Article.create(item_id: self.item_id, task_id: self.id, amount: self.item_amount)
3
  • There's no such thing as "feel right" on your example. It is very clear that when you creating the article, you are passing the item_amount as a parameter, same thing as the other ids. I can't see a reason for refactor this code.
    – MurifoX
    Jul 30, 2013 at 14:16
  • Ok good. Each task belongs to a project. Do you know a good way of summorizing the amounts for each articles belonging to the task (and the project)? Tried this and it´s not a good idea: sum = @project.tasks.map {|task| task.articles.sum(:price) }. To many queries. Jul 30, 2013 at 15:19
  • I don't know if this query will work, but give it a try. @project.joins(:tasks => [:articles]).sum('articles.price')
    – MurifoX
    Jul 30, 2013 at 17:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.