Hello guys this error is giving me a headache for days and I seriously don't know what's happening. So, I have 2 models: User and Composition. Compositions have a belongs_to :user and the user have has_many :compositions and one controller which is giving an error when I try to get de user id from the composition's owner(user).
Error
undefined method `id' for nil:NilClass
<%= link_to profile_path(compos.user.id), class: 'ui-btn btn-small' do %>
<span class="icon-export"></span>visitar perfil</a>
<% end %>
Composition
class Composition < ApplicationRecord
belongs_to :user
validates :title, presence: true, :length => {maximum: 120}
validates :description, presence: true
has_attached_file :thumbnail
validates_attachment_content_type :thumbnail, content_type: /\Aimage/
validates_attachment_file_name :thumbnail, matches: [/png\Z/, /jpe?g\Z/]
do_not_validate_attachment_file_type :thumbnail
end
User
class User < ApplicationRecord
has_many :compositions
rolify
devise :database_authenticatable, :omniauthable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
mount_uploader :avatar, AvatarUploader
# Validações
validates_integrity_of :avatar
validates_processing_of :avatar
validates_format_of :username, :with => /[\w]+/
validates_length_of :username, :in => (5..32)
validates_uniqueness_of :username
#Previne que o avatar tenha um tamanho maior de 2MB
private
def avatar_size_validation
errors[:avatar] << "should be less than 2MB" if avatar.size > 2.megabytes
end
end
Controller
class StaticPagesController < ApplicationController
before_filter :authenticate_user!
def index
#compositions = Composition.all.order('created_at desc').limit(4)
end
end
You can set if condition to check if compos.user is present.
<% if compos.user %>
But, Seems like it's data inconsistency as I think you are working on development environment
You need to make sure for each composition user_id must exist.
class Composition < ApplicationRecord
belongs_to :user
validates :user, presence: true
end
This way you will never have compos with user_id = nil
Related
this is my user model:
class User < Account
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
devise :database_authenticatable,
:ga_otp_authenticatable,
:yk_otp_authenticatable,
:registerable,
:confirmable,
:recoverable,
:trackable,
:validatable,
:lockable,
:timeoutable
# Setup accessible (or protected) attributes for your model
attr_accessible :password, :password_confirmation, :remember_me, :time_zone, :require_ga_otp, :require_yk_otp, :full_name, :address
attr_accessor :captcha,
:skip_captcha,
:new_password,
:new_password_confirmation,
:current_password
before_validation :generate_name,
:on => :create
has_many :trade_orders,
:dependent => :destroy
has_many :purchase_trades,
:class_name => "Trade",
:foreign_key => "buyer_id"
has_many :sale_trades,
:class_name => "Trade",
:foreign_key => "seller_id"
has_many :invoices,
:dependent => :destroy
has_many :yubikeys,
:dependent => :destroy
has_many :bank_accounts,
:dependent => :destroy
has_many :tickets,
:dependent => :destroy
#has_many :tickets,
# :dependent => :destroy
validates :email,
:uniqueness => true,
:presence => true
validate :captcha do
if captcha.nil? and new_record?
unless skip_captcha
errors[:captcha] << I18n.t("errors.answer_incorrect")
end
end
end
def captcha_checked!
self.captcha = true
end
def bitcoin_address
super or (generate_new_address && super)
end
def qr_code
if #qrcode.nil?
#qrcode = RQRCode::QRCode.new(bitcoin_address, :size => 6)
end
#qrcode
end
def confirm!
super
UserMailer.registration_confirmation(self).deliver
end
protected
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
name = conditions.delete(:name)
where(conditions).where(["name = :value OR email = :value", { :value => name }]).first
end
def generate_name
self.name = "BF-U#{"%06d" % (rand * 10 ** 6).to_i}"
end
end
This is my account model:
class Account < ActiveRecord::Base
has_many :account_operations
has_many :used_currencies,
:dependent => :destroy
belongs_to :parent,
:class_name => 'Account'
validates :name,
:presence => true,
:uniqueness => true
# BigDecimal returned here
def balance(currency, options = {} )
account_operations.with_currency(currency).with_confirmations(options[:unconfirmed]).with_processed_active_deposits_only.map(&:amount).sum.round(5).abs
end
# Generates a new receiving address if it hasn't already been refreshed during the last hour
def generate_new_address
unless last_address_refresh && last_address_refresh > DateTime.now.advance(:hours => -1)
self.last_address_refresh = DateTime.now
self.bitcoin_address = Bitcoin::Client.instance.get_new_address(id.to_s)
save
end
end
def max_withdraw_for(currency)
Transfer.round_amount(self.balance(currency), currency)
end
def self.storage_account_for(currency)
account_name = "storage_for_#{currency.to_s.downcase}"
account = find_by_name(account_name)
if account
account
else
Account.create! do |a|
a.name = account_name
end
end
end
end
My problem is I am trying to input the password but it is not accepting password field. It is giving error that password cant be blank.
I have tried to create user manually. here it is giving error undefined method encrypted password.
how to solve this problem?
Try out this.....
Do you have the encrypted_password column on your model?
Yes
attr_accessible :email, :password, :password_confirmation, :remember_me, :encrypted_password
Just because it's attr_accessable doesn't mean the attribute exists, just means you can access it (if it did exist). Go into your rails console and run:
User.new.respond_to?(:encrypted_password=)
If that returns true you have the column in your model, if not you need to make sure you run the correct migrations.
User.new.respond_to?(:encrypted_password=) => false
I run rake db:migrate:reset and it work!!!
I have a Thing model:
class Thing < ActiveRecord::Base
belongs_to :user
has_attached_file :image, :styles => { :medium => '300x300>', :thumb => '100x100>' }
validates :image, presence: true
validates :description, presence: true
end
I also have a User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :things
validates :name, presence: true
validates :username, presence: true
validates :email, presence: true
end
My UsersController looks like this:
class UsersController < ApplicationController
def show
#user = User.find_by_username(params[:username])
end
end
When I navigate to localhost:3000/users/Delacram, where Delacram is the username, how do I display only the Things with a username of Delacram?
Given you have the #user that has many things:
#user.things
You can loop on it:
#user.things.each do |thing|
= thing.description
...
also... in the controller, you can call an instance of #things = #user.things. Then in your view, you can call = render #things. This will look to views/things/_thing.html.haml, and plop whatever's in that file onto the page for each instance of #thing.
Rails magic...
I want to do STI in Rails.
class AbstractUser < ActiveRecord::Base
self.table_name = 'users'
belongs_to :organization, :inverse_of => :users
# reporter user
has_many :requests, :dependent => :destroy
# startup user
has_many :responses, :dependent => :destroy
has_many :startup_requests, :through => :responses, :source => :request
scope :reporters, where(:type => 'Reporter')
scope :startup_employees, where(:type => 'Startup')
scope :on_waitlist, where(:waitlist => true)
scope :not_on_waitlist, where(:waitlist => false)
end
require 'rfc822'
class User < AbstractUser
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :confirmable
validates :name, :presence => true
validates :surname, :presence => true
validates :title, :presence => true
validates :password, :presence => true, :length => { :minimum => 8 }
validates :email, :presence => true, :format => { :with => RFC822::EMAIL_REGEXP_WHOLE }
attr_accessible :name, :surname, :title, :organization,
:email, :password, :fullname
end
require 'rfc822'
class UserForAdmin < AbstractUser
validates :email, :presence => true, :format => { :with => RFC822::EMAIL_REGEXP_WHOLE }
validates :organization_id, :presence => true
attr_accessible :name, :surname, :title, :organization, :email,
:password, :fullname, :password_confirmation, :type,
:organization_id, :waitlist, :invitation_token
end
And there is some problem with these scopes.
Couldn't find UserForAdmin with id=7 [WHERE "users"."type" IN ('UserForAdmin') AND "users"."waitlist" = 'f']
I also tried to put these scopes in UserForAdmin instead of AbstractUser with the same result. I (probably) need scopes instead of custom methods, because I use them in ActiveAdmin. How can I solve this?
If you don't want to receive all users, you need to query with the base class. In a simpler example:
class Animal < ActiveRecord::Base
end
class Dog < Animal
end
class Cat < Animal
end
Dog.create
Cat.create
Animal.all
=> [dog, cat]
Dog.all
=> [dog]
Cat.all
=> [cat]
So, in your case, you'd want to:
AbstractUser.not_on_waitlist.find(params[:id])
If this user is a UserForAdmin you'll receive an object of class UserForAdmin. If it's just a user, you'll receive an object of class User
I have the following models:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
has_many :rulesets
end
class Ruleset < ActiveRecord::Base
attr_accessible :title, :game_id, :user_id
validates :game_id, presence: true
validates :user_id, presence: true
validates :title, presence: true
belongs_to :user
belongs_to :game
has_many :rules
end
class Rule < ActiveRecord::Base
attr_accessible :description, :ruleset_id
belongs_to :ruleset
validates :description, presence: true
validates :ruleset_id, presence: true
end
I have a controller called PagesController that controls the user dashboard, where I want to display the number of rulesets and number of rules that a user has. this is my controller
class PagesController < ApplicationController
def home
end
def dashboard
#rulesets = current_user.rulesets
end
end
In my dashboard view, I'm attempting to display the rulesets and rules counts as such:
<% if current_user.rulesets.any? %>
<li><%= #rulesets.count %> Ruleset</li>
<li><%= #rulesets.rules.count%> Rules</li>
<% end %>
This returns the right number of rulesets if I just try and count the rulesets. When I try and count the rules, I get this and "undefined method `rules'" error. How am I supposed to access the rules that are in the users' ruleset?
You need to count all of the rulesets and the rules for each ruleset. Use something like:
#rulesets.collect {|r| r.rules.count}.sum
Rules would be associated to a particular ruleset. You should specify the ruleset, by id, and then use the ".rules.count" to count all rules associated with THAT ruleset.
I've four user models: Zone, Product, User, Group
I want to choose what Users can sell a Product in a Zone, this is what Group does, with a many to many relation to User and a foreign key to one Product and one Zone. So I have one group per pair Zone/Product. I will also need to set custom attributes on that many to many relation so I used has_many :through Sell (I was unable to find a better name to describe the relation between Group and User).
So I ended up having 5 models: Zone, Product, User, Group, Sell.
It works fine, but now I'd need to select the next user available in a Group.
I was thinking to exploit Sell.id to find the user assigned to the same group with an higher id, if not present choose the first one again (this allows me to create a ring chain).
It would be useful to have a Group.next_user method.
Unfortunatly I can't figure out how to do this, I'd need help to find the next user available in the group (or the 1st one if there are no more users).
Follows the code for models all the models:
################
# models/group.rb
################
class Group < ActiveRecord::Base
has_many :sells
has_many :users, :through => :sells
belongs_to :zone
belongs_to :product
attr_accessible :priority, :product_id, :user_ids, :zone_id
end
################
# models/zone.rb
################
class Zone < ActiveRecord::Base
belongs_to :location
has_many :cities
has_many :groups
attr_accessible :name, :location_id
validates :location, :presence => true
end
################
# models/user.rb
################
class User < ActiveRecord::Base
after_create :create_calendar
before_destroy :destroy_calendar
belongs_to :location
belongs_to :mall
has_one :event_calendar
has_many :sells
has_many :groups, :through => :sells
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable, :registerable,
# :recoverable, :rememberable,
devise :database_authenticatable, :trackable,
:validatable, :authentication_keys => [:username]
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :password, :password_confirmation, :remember_me, :name,
:surname, :role, :location_id
# attr_accessible :title, :body
ROLES = %w[Admin Agente Hostess HostessAdmin]
validates_uniqueness_of :username, :case_sensitive => false
validates :username, :presence => true
validates_presence_of :role, :name, :surname, :location_id
validates :location, :presence => true
validates :role, :inclusion => { :in => ROLES, :message => "%{value} non è un ruolo valido." }
def display_name
"#{self.name} #{self.surname}"
end
def has_role?(role)
# convert the role string to a sybmol
self.role.downcase.gsub(/\s+/, "_").to_sym == role
end
private
def create_calendar
if self.has_role? :agente
calendar = EventCalendar.new({:user_id => self.id})
calendar.save()
end
end
def destroy_calendar
if self.has_role? :agente
calendar = EventCalendar.find_by_user_id(self.id)
calendar.destroy()
end
end
def email_required?
false
end
def email_changed?
false
end
end
################
# models/product.rb
################
class Product < ActiveRecord::Base
after_create :create_groups
before_destroy :destroy_groups
attr_accessible :name
def create_groups
for zone in Zone.all
group = Group.new({:zone_id => zone.id, :product_id => self.id})
group.save()
end
end
def destroy_groups
for zone in Zone.all
group = Group.find_by_product_id(self.id)
group.destroy
end
end
end
################
# models/sell.rb
################
class Sell < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
Can you give me some help to get this done? Thanks!
If I get this right then addd this to your User model
scope :next, lambda { |p| {:conditions => ["id > ?", p.id], :limit => 1, :order => "id"} }
and this to your group model
def self.next_user
return User.first if Group.users.blank?
next_user = User.next(Group.users.last).first
return next_user || Group.users.first
end
This should do the trick. I didn't write test for this so you should test it :)