Creating multiple habtm relationships with two models in one request - ruby-on-rails

I currently have an Album/Artist database that uses multiple join tables to signify when how an artist relates to the album. They can be listed as a Composer, an Arranger, or a Performer. That is:
class Artist < ActiveRecord::Base
...
has_and_belongs_to_many :albumbycomposers, :class_name => "Album", :join_table => "albums_composers"
has_and_belongs_to_many :albumbyarrangers, :class_name => "Album", :join_table => "albums_arrangers"
has_and_belongs_to_many :albumbyperformers, :class_name => "Album", :join_table => "albums_performers"
...
end
And
class Album < ActiveRecord::Base
has_and_belongs_to_many :composers, :class_name => "Artist", :join_table => "albums_composers"
has_and_belongs_to_many :arrangers, :class_name => "Artist", :join_table => "albums_arrangers"
has_and_belongs_to_many :performers, :class_name => "Artist", :join_table => "albums_performers"
...
end
This code is used to look up for existing artists in the database, then create the association. If no artist exists, then I use the .build method to create the artist.
class AlbumsController < ApplicationController
...
def create
#album = Album.new(params[:album])
params["Composer Names"].each do |each|
if each.empty? == false
#exists = Artist.find_by_name(each)
if #exists.nil? == true
#album.composers.build(:name => each)
else
#album.composers << Artist.find_by_name(each)
end
end
end
params["Arranger Names"].each do |each|
if each.empty? == false
#exists = Artist.find_by_name(each)
if #exists.nil? == true
#album.arrangers.build(:name => each)
else
#album.arrangers << Artist.find_by_name(each)
end
end
end
...
end
...
end
The problem I encounter occurs when I try to enter a new artist as both a composer and an arranger. For example, say I submit this as a post request
Parameters: {"Name"=>["New Album"],
"Performer Names"=>["New Artist"],
"Composer Names"=>["New Artist"],
"Arranger Names"=>["New Artist"],
...
}
Since the composer arguments are first, rails interprets them properly (as if the artist does not exist). The arranger and performer arguments are also interpreted as if the artist does not exist. Then rails begins inserting data into my database. First the album is created and inserted into the albums table, then "New Artist" is created and inserted into album_composer (according to the .build method).
However, for the arranger and performer arguments, the build method can no longer be used, since the artist has been created, so the code is not executed properly.
I tried to workaround by using the push method (aka <<) in the arranger and performer argument lines for this specific case, but that doesn't work because it instantly fires without waiting for the artist to be made by the composer argument, resulting in an "Artist cannot be found" error. For Reference:
collection<<(object, …)
Adds one or more objects to the collection by creating associations in the join table (collection.push and collection.concat are aliases to this method).
Note that this operation instantly fires update sql without waiting for the save or update call on the parent object.
What is the proper way to handle this?

I solved the problem by adding in each artist separately into my database first using the code:
#artists = params["Composer Names"] | params["Arranger Names"] | params["Performer Names"]
#artists.each do |artist|
if artist.empty? == false
#exists = Artist.find_by_name(artist)
if #exists.nil?
#artist = Artist.new(:name => artist)
#artist.save
end
end
end
I could use the push method and add each artist to the proper join table using code like:
params["Composer Names"].each do |each|
if each.empty? == false
#album.composers << Artist.find_by_name(each)
end
end
so that's that!

Related

Rails query records based on attribute of association

I'm trying to create a query based on an attribute of an associated record but am failing miserably
I've the following models:
class CompanyPay < ActiveRecord::Base
has_many :ee_pay
has_many :pay, :through => :ee_pay
end
class EePay < ActiveRecord::Base
belongs_to :company_pay
has_many :pay
end
class Pay < ActiveRecord::Base
belongs_to :ee_pay
has_one :company_pay, :through => :ee_pay
end
I'm trying to create a query that returns all Pay objects where the attribute apply_paye on their associated CompanyPay is true.
I've been trying to get my head around joins, scope, lambdas etc since yesterday but I'm just confusing myself more at the stage.
The query I want would be something like this but I just don't know how to phrase it properly
#records = Pay.where(employee_id: current_employee.id, {|p| p.company_pay.apply_paye == true}).order(:id)
Can anyone help me out. Can I write a one line query? Should I be using a join? Should a lambda be used?
Thanks for looking
Edit 1
I've edited the original post as I gave the wrong attribute name by mistake (should be apply_paye not taxable).
Tried the following query provided by fylooi
#records = Pay.joins(:ee_pay => :company_pay).where(:pay => {:employee_id => current_employee.id }, :company_pay => {:apply_paye => true})
But am getting the following error:
ActiveRecord::StatementInvalid in PayLinesController#update
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "pay" LINE 1: ...any_pays"."id" = "ee_pays"."company_pay_id" WHERE "pay"."emp... ^ : SELECT "pays".* FROM "pays" INNER JOIN "ee_pays" ON "ee_pays"."id" = "pays"."ee_pay_id" INNER JOIN "company_pays" ON "company_pays"."id" = "ee_pays"."company_pay_id" WHERE "pay"."employee_id" = 1 AND "company_pay"."apply_paye" = 't' ORDER BY "pays"."id" ASC
Edit 2 - Solved
Pluralising the table names in the query worked, as per the suggestion from David Aldridge.
This is the final query:
#records = Pay.joins(:ee_pay => :company_pay).where(:pays => {:employee_id => current_employee.id }, :company_pays => {:apply_paye => true})
Thanks for your help
Something like this?
Pay.joins(:ee_pay => :company_pay).where(:company_pay => {:taxable => true})

Ruby on Rails multiple belongs_to associations saving

There is something i don't quite understand in Rails's belongs_to concept. Documentation states:
Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object
Let's say i have an Employee entity:
class Employee < ActiveRecord::Base
belongs_to :department
belongs_to :city
belongs_to :pay_grade
end
Will the following code fire three updates and if so is there a better way to do it? :
e = Employee.create("John Smith")
Department.find(1) << e
City.find(42) << e
Pay_Grade.find("P-78") << e
You can simply assign it:
e = Employee.new(:name => "John Smith")
e.department = Department.find(1)
e.city = City.find(42)
e.pay_grade = Pay_Grade.where(:name => "P-78")
e.save
I changed the create to new to construct the object before saving it. The constructor takes a hash, not different values. find takes only the id and not a string, use where on a field instead.
You can also use the following:
Employee.create(:name => "John Smith",
:department => Department.find(1),
:city => City.find(42),
:pay_grade => PayGrade.where(:name => "P-78").first
Also note that model names should be camel case: PayGrade instead of Pay_Grade.

how to perform a somewhat complicated ActiveRecord scope query for a polymorphic association?

So, I have a Notification model that is polymorphic, and I want to be able to filter out notifications that are of a notifiable_type Comment where comment.user == current_user. In other words, I want all notification records--except for ones referring to comments that were made by the current user.
class Notification
belongs_to :notifiable, :polymorphic => true
scope :relevant, lambda { |user_id|
find(:all, :conditions => [
"notifiable_type != 'Comment' OR (notifiable_type = 'Comment' AND " <<
"comments.user_id != ?)",
user_id ],
:include => :comments
)
}
end
What I don't understand is what I need to do to get access to comments? I need to tell ActiveRecord to outer join the comment model on notifiable_id.
First, lambda scopes with parameters are deprecated. Use a class method instead:
class Notification
belongs_to :notifiable, polymorphic: true
def self.relevant(user_id)
# ...
end
end
I usually move scope functions into their own module, but you can leave it there.
Next, find(:all) is deprecated, as is :conditions. We use ActiveRelation queries now.
Unfortunately, the ActiveRecord::Relation API isn't quite robust enough to do what you need, so we'll have to drop down to ARel instead. A little bit tricky, but you definitely don't want to be doing string substitution for security reasons.
class Notification
belongs_to :notifiable, polymorphic: true
def self.relevant(user_id)
n, c = arel_table, Comment.arel_table
predicate = n.join(c).on(n[:notifiable_id].eq(c[:id]))
joins( predicate.join_sql ).
where{ ( notifiable_type != 'Comment' ) |
(( notifiable_type == 'Comment' ) & ( comments.user_id == my{user_id} ))
}
end
end
I'm using a combination of ARel and Squeel here. Squeel is so good it should be a Rails core feature. I tried writing that where clause without Squeel, but it was so difficult I gave up.
Hard to test something like this without your project handy, but hopefully that should at least get you closer.
Oops, your code has :include => :comments, plural, which threw me off. How about this?
class Notification
belongs_to :notifiable, :polymorphic => true
scope :relevant, lambda { |user_id|
find(:all, :conditions => [
"notifiable_type != 'Comment' OR (notifiable_type = 'Comment' AND " <<
"comments.user_id != ?)",
user_id ],
:include => :notifiable
)
}
end
...then Notification.relevant.first.notifiable should work. From the docs:
Eager loading is supported with polymorphic associations.
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
A call that tries to eager load the addressable model
Address.find(:all, :include => :addressable)
This will execute one query to load the addresses and load the
addressables with one query per addressable type. For example if all
the addressables are either of class Person or Company then a total of
3 queries will be executed. The list of addressable types to load is
determined on the back of the addresses loaded. This is not supported
if Active Record has to fallback to the previous implementation of
eager loading and will raise
ActiveRecord::EagerLoadPolymorphicError. The reason is that the
parent model’s type is a column value so its corresponding table name
cannot be put in the FROM/JOIN clauses of that query.
(Emphasis mine.)
This is what I've resorted to..... I am still hoping someone can show me a better way.
Notification.find_by_sql( "SELECT * from Notifications " <<
"INNER JOIN comments ON notifiable_id = comments.id " <<
"WHERE notifiable_type != 'Comment' " <<
"OR (notifiable_type = 'Comment' AND comments.user_id = '#{user_id}')"
)

Implementing rental store in Rails: how to track an inventory state over time?

Let's say you're implementing rails app for a snowboard rental store.
A given snowboard can be in one of 3 states:
away for maintenance
available at store X
on loan to customer Y
The company needs to be able to view a rental history for
a particular snowboard
a particular customer
The rental history needs to include temporal data (e.g. Sally rented snowboard 0123 from Dec. 1, 2009 to Dec. 3 2009).
How would you design your model? Would you have a snowboard table with 4 columns (id, state, customer, store), and copy rows from this table, along with a timestamp, to a snowboard_history table every time the state changes?
Thanks!
(Note: I'm not actually trying to implement a rental store; this was just the simplest analogue I could think of.)
I would use a pair of plugins to get the job done. Which would use four models. Snowboard, Store, User and Audit.
acts_as_state_machine and acts_as_audited
AASM simplifies the state transitions. While auditing creates the history you want.
The code for Store and User is trivial and acts_as_audited will handle the audits model.
class Snowboard < ActiveRecord::Base
include AASM
belongs_to :store
aasm_initial_state :unread
acts_as_audited :only => :state
aasm_state :maintenance
aasm_state :available
aasm_state :rented
aasm_event :send_for_repairs do
transitions :to => :maintenance, :from => [:available]
end
aasm_event :return_from_repairs do
transitions :to => :available, :from => [:maintenance]
end
aasm_event :rent_to_customer do
transitions :to => :rented, :from => [:available]
end
aasm_event :returned_by_customer do
transitions :to => :available, :from => [:rented]
end
end
class User < ActiveRecord::Base
has_many :full_history, :class_name => 'Audit', :as => :user,
:conditions => {:auditable_type => "Snowboard"}
end
Assuming your customer is the current_user during the controller action when state changes that's all you need.
To get a snowboard history:
#snowboard.audits
To get a customer's rental history:
#customer.full_history
You might want to create a helper method to shape a customer's history into something more useful. Maybe something like his:
def rental_history
history = []
outstanding_rentals = {}
full_history.each do |item|
id = item.auditable_id
if rented_at = outstanding_rentals.keys.delete(id)
history << {
:snowboard_id => id,
:rental_start => rented_at,
:rental_end => item.created_at
}
else
outstanding_rentals[:id] = item.created_at
end
end
history << oustanding_rentals.collect{|key, value| {:snowboard_id => key,
:rental_start => value}
end
end
First I would generate separate models for Snowboard, Customer and Store.
script/generate model Snowboard name:string price:integer ...
script/generate model Customer name:string ...
script/generate model Store name:string ...
(rails automatically generates id and created_at, modified_at dates)
To preserve the history, I wouldn't copy rows/values from those tables, unless it is necessary (for example if you'd like to track the price customer rented it).
Instead, I would create SnowboardEvent model (you could call it SnowboardHistory if you like, but personally it feels strange to make new history) with the similiar properties you described:
ev_type (ie. 0 for RETURN, 1 for MAINTENANCE, 2 for RENT...)
snowboard_id (not null)
customer_id
store_id
For example,
script/generate model SnowboardEvent ev_type:integer snowboard_id:integer \
customer_id:integer store_id:integer
Then I'd set all the relations between SnowboardEvent, Snowboard, Customer and Store. Snowboard could have functions like current_state, current_store implemented as
class Snowboard < ActiveRecord::Base
has_many :snowboard_events
validates_presence_of :name
def initialize(store)
ev = SnowboardEvent.new(
{:ev_type => RETURN,
:store_id => store.id,
:snowboard_id = id,
:customer_id => nil})
ev.save
end
def current_state
ev = snowboard_events.last
ev.ev_type
end
def current_store
ev = snowboard_events.last
if ev.ev_type == RETURN
return ev.store_id
end
nil
end
def rent(customer)
last = snowboard_events.last
if last.ev_type == RETURN
ev = SnowboardEvent.new(
{:ev_type => RENT,
:snowboard_id => id,
:customer_id => customer.id
:store_id => nil })
ev.save
end
end
def return_to(store)
last = snowboard_events.last
if last.ev_type != RETURN
# Force customer to be same as last one
ev = SnowboardEvent.new(
{:ev_type => RETURN,
:snowboard_id => id,
:customer_id => last.customer.id
:store_id => store.id})
ev.save
end
end
end
And Customer would have same has_many :snowboard_events.
Checking the snowboard or customer history, would be just a matter of looping through the records with Snowboard.snowboard_events or Customer.snowboard_events. The "temporal data" would be the created_at property of those events. I don't think using Observer is necessary or related.
NOTE: the above code is not tested and by no means perfect, but just to get the idea :)

Removing one of the many duplicate entries in a habtm relationship?

For the purposes of the discussion I cooked up a test with two tables:
:stones and :bowls (both created with just timestamps - trivial)
create_table :bowls_stones, :id => false do |t|
t.integer :bowl_id, :null => false
t.integer :stone_id, :null => false
end
The models are pretty self-explanatory, and basic, but here they are:
class Stone < ActiveRecord::Base
has_and_belongs_to_many :bowls
end
class Bowl < ActiveRecord::Base
has_and_belongs_to_many :stones
end
Now, the issue is: I want there to be many of the same stone in each bowl. And I want to be able to remove only one, leaving the other identical stones behind. This seems pretty basic, and I'm really hoping that I can both find a solution and not feel like too much of an idiot when I do.
Here's a test run:
#stone = Stone.new
#stone.save
#bowl = Bowl.new
#bowl.save
#test1 - .delete
5.times do
#bowl.stones << #stone
end
#bowl.stones.count
=> 5
#bowl.stones.delete(#stone)
#bowl.stones.count
=> 0
#removed them all!
#test2 - .delete_at
5.times do
#bowl.stones << #stone
end
#bowl.stones.count
=> 5
index = #bowl.stones.index(#stone)
#bowl.stones.delete_at(index)
#bowl.stones.count
=> 5
#not surprising, I guess... delete_at isn't part of habtm. Fails silently, though.
#bowl.stones.clear
#this is ridiculous, but... let's wipe it all out
5.times do
#bowl.stones << #stone
end
#bowl.stones.count
=> 5
ids = #bowl.stone_ids
index = ids.index(#stone.id)
ids.delete_at(index)
#bowl.stones.clear
ids.each do |id|
#bowl.stones << Stone.find(id)
end
#bowl.stones.count
=> 4
#Is this really the only way?
So... is blowing away the whole thing and reconstructing it from keys really the only way?
You should really be using a has_many :through relationship here. Otherwise, yes, the only way to accomplish your goal is to create a method to count the current number of a particular stone, delete them all, then add N - 1 stones back.
class Bowl << ActiveRecord::Base
has_and_belongs_to_many :stones
def remove_stone(stone, count = 1)
current_stones = self.stones.find(:all, :conditions => {:stone_id => stone.id})
self.stones.delete(stone)
(current_stones.size - count).times { self.stones << stone }
end
end
Remember that LIMIT clauses are not supported in DELETE statements so there really is no way to accomplish what you want in SQL without some sort of other identifier in your table.
(MySQL actually does support DELETE ... LIMIT 1 but AFAIK ActiveRecord won't do that for you. You'd need to execute raw SQL.)
Does the relationship have to be habtm?
You could have something like this ...
class Stone < ActiveRecord::Base
has_many :stone_placements
end
class StonePlacement < ActiveRecord::Base
belongs_to :bowl
belongs_to :stone
end
class Bowl < ActiveRecord::Base
has_many :stone_placements
has_many :stones, :through => :stone_placements
def contents
self.stone_placements.collect{|p| [p.stone] * p.count }.flatten
end
def contents= contents
contents.sort!{|a, b| a.id <=> b.id}
contents.uniq.each{|stone|
count = (contents.rindex(stone) - contents.index(stone)) + 1
if self.stones.include?(stone)
placement = self.stone_placements.find(:first, :conditions => ["stone_id = ?", stone])
if contents.include?(stone)
placement.count = count
placement.save!
else
placement.destroy!
end
else
self.stone_placements << StonePlacement.create(:stone => stone, :bowl => self, :count => count)
end
}
end
end
... assuming you have a count field on StonePlacement to increment and decrement.
How about
bowl.stones.slice!(0)

Resources