I have:
User id:integer name:integer
class User
has_many :complete_tasks
end
Task id:integer style:string uid:string
CompleteTask id:integer style:string uid:string user_id:integer
class CompleteTask
belongs_to :user
end
i have some records in DB
user = User.first
id:1 name:Den
tasks = Tasks.all
id:1 style => "run" uid => "river"
id:2 style => "jump" uid => "sea"
id:3 style => "run" uid =>"sea"
id:4 style => "run" uid =>"river"
id:5 style => "run" uid =>"forest"
user.complete_tasks.all
id:1 style => "run" uid => "river" user_id => 1
id:2 style => "jump" uid => "sea" user_id => 1
How to get records from Task where fields :style and :uid together not equivalent fields :style and :uid in model CompleteTask.
This is a poor database model and i would recommend to use something else. Maybe a boolean value or smthng like that in the task model so you can check if it's complete or not.
Anyways, here is a solution:
all_tasks = Task.all
complete_tasks = CompleteTask.all
complete_tasks.each do |complete_task|
#find if there is a task with the corresponding uid and style in the complete tasks
tasks = all_tasks.where(:uid => complete_task.uid, :style => complete_task.style)
#remove it from all_tasks (all_tasks means tasks that haven't finished yet)
all_tasks = #all_tasks - tasks
end
return all_tasks
If I'm understanding you correctly, you're trying to find all tasks that don't have the same IDs as complete tasks.
For that you should use a find condition--something like:
Task.find(:all, :conditions => { :complete => false });
Related
I am using a rakefile to fetch information from one website and saving it to my database.
Using the TMDB-Gem, this code #movie = TmdbMovie.browse(:order_by => "release", :order => "asc", :page => 1, :per_page => 2, :language => "en", :expand_results => true) browses the oldest movies (:order_by => "release") and saves them to my database, but as i'll be running this rake quite frequently, the returned and saved movies will be the same.
Every movie has a tmdb_id and every id is unique
How can i make the rakefile check that the returned movie's tmdb_id is unique, and if there is already a movie with that id, skip and save the next movie.
I tried it in my Movies model validates_uniqueness_of :tmdb_id but it gives an error when running the rake command and it doesn't save movies.
Basically, how can I, through the rakefile, validate the uniqueness of the tmdb_id
This is my rake file
namespace :db do
task :pull_tmdb_data => :environment do
Tmdb.api_key = "API KEY"
Tmdb.default_language = "en"
#movie = TmdbMovie.browse(:order_by => "release", :order => "asc", :page => 1, :per_page => 2, :language => "en", :expand_results => true)
#movie.each do |movie|
Movie.create(title: movie.name, description: movie.overview, release_date: movie.released, tmdb_id: movie.id)
end
end
end
You're right to use validates_uniqueness_of :tmdb_id in your Movie model. You didn't show how you were saving the movies to your database, but .save doesn't cause an exception when validations fail, whereas .save! does. The key would be to use a save method that doesn't raise an error when validations fail.
Edit - Now that I understand what you're actually trying to do, you should be able to do something like:
per_page = 100
number_of_movies = Movie.count
page = number_of_movies/per_page+1
#movies = TmdbMovie.browse(:order_by => "release", :order => "asc", :page => page, :per_page => per_page, :language => "en", :expand_results => true) browses the oldest movies (:order_by => "release")
So if you've already pulled 435 movies, it'll only return movies 400-500 in the next call .. I did it this way because I wasn't sure if there was an offset option, but if there is you could just offset the query by Movie.count, which would be better.
This is just a simple question. I was trying to create a new object in Rails by passing in parameters to the constructor. However, when I execute the code, I get
SQLite3::SQLException: no such column: awards.user_id: SELECT "awards".* FROM "awards" WHERE "awards"."user_id" = 1
which means the object isn't being constructed properly. Should I be using create instead of new? That isn't working either.
def refresh_awards(user)
new_awards = []
if (user.karma < 40 ) #test award
a = Award.new(:name => "Nobody Award", :description => "From Jonathan", :category => "Community", :value => 1337, :level => 0, :handle => "nobody_award")
user.awards.append(a)
new_awards.append(a)
end
new_awards.each do |a|
flash[:notice] = "You received the " + a.name + "!"
end
end
Have you add has_many :awards to the User model? Have you added belongs_to :user to the Award model? Have you added the column user_id to the Award model (using a migration)? You'll need to do these three things to be able to use the user.awards method you're using. Read the Rails Guide on Associations for more detail.
Also, append isn't a Ruby method - the closest method would be <<. You would use it like this:
a = Award.new(:name => "Nobody Award", :description => "From Jonathan", :category => "Community", :value => 1337, :level => 0, :handle => "nobody_award")
user.awards << a
But you could neaten this into one line of code using the create method:
a = user.awards.create(:name => "Nobody Award", :description => "From Jonathan", :category => "Community", :value => 1337, :level => 0, :handle => "nobody_award")
EDIT: To create the user_id column in the Award model, run the following code from terminal (while in your app's directory):
rails generate migration AddUserIdToAward user_id:integer
rake db:migrate
I would like to seed my Products and assign them to a specific User and Store.
Product.rb
class Product < ActiveRecord::Base
belongs_to :user
belongs_to :store
def product_store=(id)
self.store_id = id
end
end
Note: Store belongs_to Business (:business_name)
Seed.rb
This is my basic setup:
user = User.create(:username => 'user', :email => 'user2#email.com')
store = Store.create(:business_name => 'store', :address => 'Japan')
I attempted these but they did not work:
# This gives random ID's ranging from 1 to 4425!?
user.products.create([{:name => "Apple", :product_store => Store.find_by_address('San Francisco, USA')}])
# This gives me undefined method 'walmart'.
user.store.products.create([ {:name => "Apple"} ])
Is there a way to set the ID's so I can associate my Products to a Store and User?
UPDATE -
I have tried the answers below and still came out unsuccessful. Does anyone know of another way to do this?
Although it sounds like you found a workaround, the solution may be of interested to others.
From your original seeds.rb
user = User.create(:username => 'user', :email => 'user2#email.com')
store = Store.create(:business_name => 'store', :address => 'Japan')
Create the store
Store.create({
user_id: user.id
store_id: store.id
}, without_protection: true)
In the original code snipped "user" and "store" variables are declared. The code assigns user_id / store_id (the model columns inferred by the belongs_to relationship in the Store model) to the id values that are present in the "user" and "store" variables.
"without_protection: true" turns off bulk assignment protection on the id fields. This is perfectly acceptable in a seeds file but should be used with extreme caution when dealing with user provided data.
Or alternatively create your stores.
Then extract the correct one
e.g.
store = Store.find_by_business_name('Test Store')
and then create it based on that
e.g.
store.products.create(:product_name => "Product Test", :price => '985.93')
This will then set the relationship id for you,
If I'm not mistaken, you're just trying to do this.
user = User.create(:username => 'usertwo', :email => 'user2#email.com')
walmart = Store.create(:business_name => 'Walmart', :address => 'San Francisco, USA')
user.products.create(:name => 'Apple', :store => walmart)
Anything else required here that I'm not seeing?
Try doing this
store_1 = Store.new(:business_name => 'Test Store',
:address => 'Test Address',
:phone_number => '555-555-555')
store_1.id = 1
store_1.save!
The trick is not to set the id within the hash as it is protected.
Scott
What I did was update the particular products to a certain user, see this question:
Can I update all of my products to a specific user when seeding?
You could just create a series of insert satements for this "seed migration", including the record Id for each user, store, product etc. You might have to update database sequences after this approach.
Another approach
Create the initial records in you Rails app, through the GUI / web.
Then use something like Yaml-db. So you can dump the data to a yaml file. You can now edit that file (if necessary) and use that same file to seed another instance of the db with "rake db:load"
Either way.... You know the Ids will not be shifting around on you when these objects are created in the new db instance.
I'm sure there are other ways to do this... Probably better ones, even.
Here is a link to a write-up I did a while back for using yaml_db to seed an oracle database
http://davidbharrison.com/database_seeding_oracle
Try this:
User.destroy_all
Product.destroy_all
user = User.create!([{:username => 'usertwo', :email =>'user2#email.com'},
{:username => 'userthree', :email => user3#email.com}])
user.each_with_index do |obj, index|
Product.create!([{ :product_name => 'product #{index}', :user_id => obj.id }])
end
The table would look like this:
Here's how I prefer to seed an association in rails 6
#teacher = Teacher.new(name: "John")
#student = #teacher.build_student(name: "Chris")
#teacher.save!
#student.save!
I've got a Person model, who has_many roles, and roles, in turn, belong_to an application. I'd like to query all the roles a person has for a given application. So far I've got:
p = Person.includes(:roles => [:application]).where(:loginid => 'their_loginid', :roles => {:application_id => 1})
Which works, but it's querying based on Person.roles.application_id; instead, I'd like to query based on Person.roles.application.api_key (another property of an application).
I tried:
p = Person.includes(:roles => [:application]).where(:loginid => 'their_loginid', :roles => {:application => {:api_key => 'the_api_key'}})
but I receive the error that:
no such column: application.api_key
leading me to think my usage of ActiveRecord isn't joining the tables together correctly.
Any ideas?
Try this:
p = Person.includes(:roles => [:application]).where(:loginid => 'their_loginid', :role_id => Application.find_by_api_key('api_key').role_ids)
try this
p = Person.joins.includes(:roles => [:application]).where(:loginid => 'their_loginid', :roles => {:application => {:api_key => 'the_api_key'}})
In my case it woks.
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 :)