Skip to content

Instantly share code, notes, and snippets.

@willbuilds
Last active August 29, 2015 14:17
Show Gist options
  • Save willbuilds/baf2d92e864cdf04066f to your computer and use it in GitHub Desktop.
Save willbuilds/baf2d92e864cdf04066f to your computer and use it in GitHub Desktop.
Custom builder method for an ActiveRecord association (Logic localised to has_many's class)
class Line << ActiveRecord::Base
belongs_to :group
belongs_to :product
def build_for_product(product_id)
product = Product.find(product_id)
line = Line.new(
:product => product,
:line_type => 'stock',
:quantity => 1,
:order_unit => product.stock_unit,
:unit_price_cents => product.sell_price_cents,
:price_basis => 'extax'
)
line
end
end
class Group << ActiveRecord::Base
has_many :lines do
def build_for_product(product_id)
# Build a line using a custom build method 'build_for_product()' class method on Line
# IE @group.lines.build_for_product(123)
# line can either be saved via line, or via group.save
self.build(Line.build_for_product(product_id).attributes)
end
end
end
## Example
group = Group.first
line = group.lines.build_for_product(13)
line # <#Line id: nil, group_id: 5, line_type: "stock", state: "dispatching", product_id: 13, quantity: 1, order_unit: nil, unit_price_cents: 0, currency: "AUD", price_basis: nil, created_at: "2015-03-26 02:10:16", updated_at: "2015-03-26 02:10:17">
group.save OR line.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment