Created
December 10, 2011 17:47
-
-
Save andruu/1455742 to your computer and use it in GitHub Desktop.
I have a post model which has_many comments and a comment model which belongs_to a user and I am looping through the comments trying to get the users information. if i do comment.user.to_yaml I can see all of the attributes but when I try to get the usern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
show.html.slim | |
- @post.comments.each do |comment| | |
div.comment | |
# Works and shows user attributes | |
/ --- !ruby/object:User | |
/ aggregation_cache: {} | |
/ | |
/ association_cache: {} | |
/ | |
/ attributes: | |
/ id: 17 | |
/ username: andrew | |
/ email: [email protected] | |
/ created_at: 2011-12-07 15:28:11.556687 | |
/ updated_at: 2011-12-07 15:28:11.556687 | |
/ password_digest: xxx | |
/ avatar: | |
/ attributes_cache: {} | |
/ | |
/ changed_attributes: {} | |
/ | |
/ destroyed: false | |
/ marked_for_destruction: false | |
/ new_record: false | |
/ previously_changed: {} | |
/ | |
/ readonly: false | |
/ relation: | |
= comment.user.to_yaml | |
# Doesn't work and gives error: undefined method `username' for nil:NilClass | |
= comment.user.username | |
= comment.body | |
comment.rb | |
class Comment < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :post, counter_cache: :comment_count | |
end | |
user.rb | |
class User < ActiveRecord::Base | |
mount_uploader :avatar, ImageUploader | |
attr_accessible :email, :username, :password, :password_confirmation, :avatar | |
has_secure_password | |
has_many :posts | |
has_many :authentications | |
has_many :comments | |
validates :username, presence: true, | |
uniqueness: true, | |
length: { in: 4..20 } | |
validates :email, presence: true, | |
uniqueness: true, | |
format: { with: /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i } | |
validates :password, presence: true, on: :create | |
def self.find_by_email_or_username (email_or_username) | |
where('email = ? OR username = ?', email_or_username, email_or_username).first | |
end | |
def setup_omniauth(omniauth) | |
self.username = omniauth[:info][:nickname] if omniauth[:info][:nickname] | |
self.email = omniauth[:info][:email] if omniauth[:info][:email] | |
end | |
def apply_omniauth(omniauth) | |
authentications.build(provider: omniauth[:provider], uid: omniauth[:uid]) | |
self.remote_avatar_url = omniauth[:info][:image] if omniauth[:info][:image] && !avatar | |
end | |
def to_param | |
username.parameterize | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment