In my Rails 3 project I have three models: Projects has_many Feeds, and Feeds has_many XML_Fields. I have an entry in the Projects table with :name
= "TestProject". I am running a script located in /app/ using rails 开发者_如何学JAVArunner, and I am trying to access the database entries with ActiveRecord:
class Testing < ActiveRecord::Base
project = Project.find_by_name("TestProject")
puts project
end
Whether I use find_by_name
, find
, where
, or whatever, my results always end up looking like:
#<Project:0x00000102b30ad0>
How do I get ActiveRecord to return the actual contents of that db entry (e.g. I want it to put "TestProject")?
Your output is perfectly fine. You are simply getting inspect output for your model. You have two options to get the desired output:
puts project.name
or redefine to_s:
def to_s
name
end
you could try project.to_yaml or p project or project.inspect depending on your needs.
puts just prints the object instance to stdout in this case an instance of Project, if you would use puts project.name it would print the return value of the method name of the instance to $stdout
精彩评论