I have a requirement for users to be able to search file names uploaded by paperclip. Looking at an uploaded document looks like this...
2.0.0-p353 :002 > d=Document.last
Document Load (0.4ms) SELECT "documents".* FROM "documents" ORDER BY "documents"."id" DESC LIMIT 1
=> #<Document id: 5, name: "hampton_george_27_70", transcription: "Asheville Nov 8th 1853 received of James A. Patton...", created_at: "2014-08-22 16:10:19", updated_at: "2014-08-22 16:37:51", document_file_name: "hampton_george_27_70.jpeg", document_content_type: "image/jpeg", document_file_size: 519652, document_updated_at: "2014-08-22 16:10:19">
2.0.0-p353 :003 > d.document_file_name
=> "hampton_george_27_70.jpeg"
But these are no traditional rails type models, so how would I go about searching them?
Document appears to be a model, so you can query it. For example, to search for documents with "george" in the file name:
search_term = "george"
documents = Document.where(['document_file_name LIKE ?', "%#{search_term}%"])
Related
I have created a Ruby on Rails job (extending from ActiveJob::Base) that parses a CSV file and inserts its rows as records (Students) in a database. That is working as expected.
However, when I try to fetch another object from the DB (the Career for each Student, which is part of each CSV row as a pair (career_code, career_name)), I'm getting this error:
undefined method 'find_by' for Career:Class
(I have also tried using Career.where instead).
I find this quite strange, since I'm already saving my Student, which is also an ActiveRecord::Base child class.
Here's the relevant part of my job:
ActiveRecord::Base.transaction do
student_hash.keys.each do |k|
some_student = student_hash[k]
student = Student.new
student.csv_id = some_student.id
student.first_name = some_student.first_name
student.last_name = some_student.last_name
student.file_number = some_student.file_number
# student.career = Career.where(code: some_student.career_code)
student.career = Career.find_by code: some_student.career_code
puts student.save! # Why this works, and the above line doesn't?
end
end
And also, the desired output, as I can see it in the Rails console:
Loading development environment (Rails 4.2.4.rc1)
2.1.3 :001 > Career.where(code: 11)
Career Load (0.5ms) SELECT "careers".* FROM "careers" WHERE "careers"."code" = ? [["code", 11]]
=> #<ActiveRecord::Relation [#<Career id: 4, name: "Informática", created_at: "2015-09-30 22:05:07", updated_at: "2015-09-30 22:05:07", code: 11>]>
2.1.3 :002 > Career.where code: 11
Career Load (0.2ms) SELECT "careers".* FROM "careers" WHERE "careers"."code" = ? [["code", 11]]
=> #<ActiveRecord::Relation [#<Career id: 4, name: "Informática", created_at: "2015-09-30 22:05:07", updated_at: "2015-09-30 22:05:07", code: 11>]>
2.1.3 :003 > Career.find_by code: 11
Career Load (0.4ms) SELECT "careers".* FROM "careers" WHERE "careers"."code" = ? LIMIT 1 [["code", 11]]
=> #<Career id: 4, name: "Informática", created_at: "2015-09-30 22:05:07", updated_at: "2015-09-30 22:05:07", code: 11>
2.1.3 :004 >
Probably this is a really stupid question, but I'm quite a beginner using Rails. Do I need to import some sort of "Context" (this seems unlikely, since Student seems to be properly resolved)? I'm using Rails 4.2.4.rc1 by the way.
Thanks in advance
Any chance at that point in the code Career isn't an AR, but some other class? That would at least explain why the methods don't exist.
I start to using pry in a rails console.
When I get a instance of a Rails model, the values are shown without line breaks like this:
pry(#<Class:0x1022f60e0>):1> first
=> #<Article id: 1, name: "What is Music", content: "Music is an art form in which the medium is sound o...", created_at: "2011-08-24 20:35:29", updated_at: "2011-08-24 20:37:22", published_at: "2011-05-13 23:00:00">
from http://railscasts.com/episodes/280-pry-with-rails?view=asciicast
Is there way to show the values with line breaks like this?
Article
id: 1
name: "What is Music"
content: "Music is an art form in which the medium is sound o..."
created_at: "2011-08-24 20:35:29"
updated_at: "2011-08-24 20:37:22"
published_at: "2011-05-13 23:00:00"
You could call .to_yaml on the model instance! It returns a string that's formatted almost exactly like you're requesting it to be.
Here are some examples of to_yaml output:
http://yaml4r.sourceforge.net/doc/page/examples.htm
I would recommend that you install awesome_print.
Add it to your Gemfile:
group :development do
gem 'awesome_print'
end
And install it with bundle install.
Now use ap to print it in the console:
pry(#<Class:0x1022f60e0>):1> ap first
#<Article:0x1022f60e0> {
:id => 1,
:name => "What is Music"
:content => "Music is an art form in which the medium is sound o..."
:created_at => "2011-08-24 20:35:29"
:updated_at => "2011-08-24 20:37:22"
:published_at => "2011-05-13 23:00:00"
}
I think, the below trick will work for you.
arup#linux-wzza:~/Rails/model_prac> rails c
Loading development environment (Rails 4.1.4)
2.1.2 :001 > Comment.first
Comment Load (0.4ms) SELECT "comments".* FROM "comments" ORDER BY "comments"."id" ASC LIMIT 1
=> #<Comment id: 1, value_old: "I am a good Boy.", value_new: "I am a bad Boy.", created_at: "2014-08-02 17:36:14", updated_at: "2014-08-02 18:21:42">
2.1.2 :002 > y Comment.first
Comment Load (0.4ms) SELECT "comments".* FROM "comments" ORDER BY "comments"."id" ASC LIMIT 1
--- !ruby/object:Comment
attributes:
id: 1
value_old: I am a good Boy.
value_new: I am a bad Boy.
created_at: 2014-08-02 17:36:14.249466000 Z
updated_at: 2014-08-02 18:21:42.511522000 Z
=> nil
2.1.2 :003 >
I am writing a script that will be in charge of transferring data from production db to a new production db.
There is one Rails app connecting to each database. In the new app we have made some migrations that change the schema (remove columns, etc)
I tried to do this:
rails console old
2.0.0p247 :004 > tag = Tag.last.dup
=> #<Tag id: nil, description: " views", account_id: 46, screenshotBase64: "", user_id: 1, created_at: nil, updated_at: nil>
2.0.0p247 :005 > ActiveRecord::Base.establish_connection(:development)
2.0.0p247 :006 > tag.save
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'screenshotBase64' in 'field list
As we removed the screenshotBase64 in the new db, it does not work.
Is there a way to do that with Rails ? Delete attributes from Rails model before save ?
Is there a better way to transfer all data from a user linked through its associations between two databases (changing ids in the new db) ?
Please have a try with this code
tag_attributes = Tag.last.attributes.dup
%w(id screenshotBase64).map{|method| tag_attributes.delete method}
ActiveRecord::Base.establish_connection(:development)
tag = Tag.create(tag_attributes)
i'm trying to implement simple search function with thinking sphinx, basing on this. i managed to set sphinx up, but when i try it in a console, 0 results are found every time. i'm wondering what is wrong here...
indices/news_post_index.rb:
ThinkingSphinx::Index.define :news_post, :with => :active_record do
indexes title
indexes content
end
and the rails console output:
2.0.0p0 :013 > NewsPost.create!(title: "awesome post", content: "this post is awesome and you know it", published_at: "2001-01-01")
(0.3ms) BEGIN
NewsPost Exists (60.7ms) SELECT 1 AS one FROM `news_posts` WHERE `news_posts`.`slug` = 'awesome-post' LIMIT 1
SQL (48.3ms) INSERT INTO `news_posts` (`content`, `created_at`, `published_at`, `slug`, `title`, `updated_at`) VALUES ('this post is awesome and you know it', '2013-09-10 08:18:35', '2001-01-01', 'awesome-post', 'awesome post', '2013-09-10 08:18:35')
(40.1ms) COMMIT
=> #<NewsPost id: 2, published_at: "2001-01-01", content: "this post is awesome and you know it", title: "awesome post", created_at: "2013-09-10 08:18:35", updated_at: "2013-09-10 08:18:35", slug: "awesome-post">
2.0.0p0 :014 > NewsPost.search "awesome post"
Sphinx Query (0.9ms) SELECT * FROM `news_post_core` WHERE MATCH('awesome post #sphinx_internal_class_name (NewsPost)') AND `sphinx_deleted` = 0 LIMIT 0, 20
Sphinx Found 0 results
=> []
From what i understand title is indexed, and so I should be able to search for it. but no matter what my key is, results are always empty array, no results at all...
Run rake ts:index after every update, then search.
It appears some of my seeds are not saving. For starters, I will show a console session so you can see that the 'instructor_id' is indeed being set in the console, but not when I seed.
ruby-1.9.2-p180 :015 > c = Course.find 2
Course Load (1.6ms) SELECT "courses".* FROM "courses" WHERE "courses"."id" = $1 LIMIT 1 [["id", 2]]
=> #<Course id: 2, name: "Microcomputers II Lab", course_code: "CE-420L", instructor_id: nil, school_id: nil, created_at: "2011-06-04 19:40:32", updated_at: "2011-06-04 19:40:32">
ruby-1.9.2-p180 :016 > c.instructor = Instructor.first
Instructor Load (0.6ms) SELECT "instructors".* FROM "instructors" LIMIT 1
=> #<Instructor id: 1, name: "Instructor Name", created_at: "2011-06-04 19:40:32", updated_at: "2011-06-04 19:40:32">
ruby-1.9.2-p180 :017 > c
=> #<Course id: 2, name: "Microcomputers II Lab", course_code: "CE-420L", instructor_id: 1, school_id: nil, created_at: "2011-06-04 19:40:32", updated_at: "2011-06-04 19:40:32">
From looking at the console, you can see that when I call c.instructor = Instructor.first, it is correctly setting my instructor_id.
Now, in the seeds file I have variables. (This is just a snippet)
### Instructors ###
puts "Creating Instructors"
instructor_1 = Instructor.find_or_create_by_name("Instructor Name")
### Courses ###
puts "Creating Courses"
ce420L = Course.find_or_create_by_name("Microcomputers II Lab", :course_code => "CE-420L")
### Add the Instructor to the Course ###
puts "Adding an Instructor to the Courses"
ce420L.instructor = instructor_1
But when I run the seeds using 'rake db:seed', it is correctly creating all of my models, and most of my relationships. But it is not setting the instructor properly.
Thoughts?
EDIT:
Just tried:
ce420 = Course.find_or_initialize_by_name("Microcomputers II")
ce420.instructor_id = instructor_1.id
ce420.save!
And it did not save my instructor.
Here are my models.
class Instructor < ActiveRecord::Base
### ASSOCIATIONS ###
has_many :courses
end
class Course < ActiveRecord::Base
belongs_to :instructor
end
Did you run...
ce420L.save!
... after assigning the instructor?
Much faster to do this:
### Courses ###
puts "Creating Courses belonging to Instructor 1"
ce420L = Course.find_or_initialize_by_name("Microcomputers II Lab") :course_code => "CE-420L")
ce420L.instructor_id = instructor_1.id
ce420L.save
Note the following:
You had an errant comma after your find_or_create on ce420L.
Doing the assignment together with the course creation prevents the system from validating and saving ce420L twice.
You can try assigning the specific ID as I did, i.e. ce420L.instructor_id = ...
If this doesn't work, check your Instructor Model to ensure you don't have any callbacks getting in the way.