Rails 3: Difference between revisions

From Wiki
Jump to navigation Jump to search
No edit summary
Blanked the page
 
Line 1: Line 1:


== Active Record ==
=== Create and Save ===
<source lang="ruby">
article = Article.new  # make an empty object
article.title = "My Title"  # add attributes
article.author = "Herman"
article.save  # save to database
</source>
<source lang="ruby">
article.create(:title => "My Title", :author => "Herman")  # make, set attributes, and save
</source>
<source lang="ruby">
article.new_record?  # new means not saved to database
</source>
=== Find ===
<source lang="ruby">
Article.find(3)                # look for id = 3
Article.first                  # same as Article.find(:first), uses "LIMIT 1" in SQL, so may not be id = 1
Article.last                  # same as Article.find(:last)
Article.all                    # same as Article.find(:all)
Article.where(:title => 'RailsConf').first  # chaining
Article.find_by_title('RailsConf')  # dynamic finder
</source>
=== Update ===
<source lang="ruby">
article = Article.first
article.title = "Rails 3 is great"
article.published_at = Time.now
article.save
</source>
<source lang="ruby">
article = Article.first
article.update_attributes(:title => "RailsConf2010", :published_at => 1.day.ago)  # saves too
</source>
=== Delete ===
<source lang="ruby">
Article.find(3).destroy  # find, then destroy
Article.destroy(3)      # same thing
Article.delete(3)        # delete directly from database with no object callbacks
Article.delete_all("published_at < '2011-01-01'")  # conditional
</source>
=== Validation and Errors ===
<source lang="ruby">
class Article< ActiveRecord::Base
    validates :title, :presence => true
    validates :body, :presence => true
end
</source>
<source lang="ruby">
article = Article.new
article.errors.any?          # false
article.save                  # returns false because of validation
article.errors.full_messages  # ["Title can't be blank", "Body can't be blank"]
article.errors.on(:title)    # "can't be blank"
article.valid?                # false
</source>
=== Associations ===
==== One-to-one ====
<source lang="ruby">
class User < ActiveRecord::Base
    has_one :profile          # assumes User.profile_id column
end                            # creates User.profile method
-------------------------------
class Profile < ActiveRecord::Base
    belongs_to :user          # assumes Profile.user_id column
end                            # creates Profile.user method
</source>
==== One-to-many ====
<source lang="ruby">
class Message < ActiveRecord::Base
    has_many :attachments        # creates Message.attachments method
end
-------------------------------
class Attachment < ActiveRecord::Base
    belongs_to :message          # assumes Attachment.message_id column
end                              # creates Attachment.message method
</source>

Latest revision as of 21:02, 28 June 2011