I am pretty new to Rails and I have stumbled upoun this problem. I'm guessing it's going to be relatively simple to you pros. I have a model named User and this has all the user attributes in it. I also created a model called list and now I want to. I am now trying to call the method create from the user buy doing something like this below (all happening in the console)
sample = User.create(#attributes here)
newlist = sample.List.create(#attributes here)
i then get this error
irb(main):011:0> sample.Lists.new
NoMethodError: undefined method `Lists' for #<User:0x4146750>
Below are my model files for User and List
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# firstName :string(255)
# middleName :string(255)
# lastName :string(255)
# email :string(255)
# facebookexternalId :integer
# userType :integer
# gender :string(255)
# description :string(255)
# location :string(255)
# image :string(255)
# password :string(255)
# notificationId :string(255)
# disabled :boolean
# disabledNotes :string(255)
# city :string(255)
# country :string(255)
# joinDate :string(255)
# created_at :datetime not null
# updated_at :datetime not null
class User < ActiveRecord::Base
attr_accessible :firstName, :middleName , :lastName ,:email , :facebookexternalId, :gender , :description, :location , :image , :city, :country, :disabled
email_regex= /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :firstName , :presence =>true,
:length => {:maximum => 45}
validates :lastName , :presence =>true,
:length => {:maximum => 45}
validates :email , :presence =>true,
:format =>{:with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :description, :length => {:maximum => 140}
has_many :lists
end
Lists
# == Schema Information
#
# Table name: lists
#
# id :integer not null, primary key
# name :string(255)
# user_Id :integer
# active :boolean
# type :string(255)
# description :string(255)
# roughList :boolean
# created_at :datetime not null
# updated_at :datetime not null
#
class List < ActiveRecord::Base
belongs_to :user
end
You should use list in it's plural form which would be something like,
sample_user.lists.create ...
or
sample_user.lists.new
like how you named it in the :has_many
Related
I'm using the version of that gem https://github.com/crowdint/acts_as_shopping_cart for rails 3
I did everything with the conventions names. But I'm getting the error Can't mass-assign protected attributes: item
class ShoppingCartsController < ApplicationController
before_filter :extract_shopping_cart
def create
#product = Video.find(params[:product_id])
#shopping_cart.add(#product, #product.price) # the error is generated on that line
redirect_to shopping_cart_path
end
My model ShoppingCart:
# == Schema Information
#
# Table name: shopping_carts
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
#
class ShoppingCart < ActiveRecord::Base
acts_as_shopping_cart
attr_accessible :price
#accepts_nested_attributes_for :price
end
My model ShoppingCartItem:
# == Schema Information
#
# Table name: shopping_cart_items
#
# id :integer not null, primary key
# owner_id :integer
# owner_type :string(255)
# quantity :integer
# item_id :integer
# item_type :string(255)
# price :float
# created_at :datetime not null
# updated_at :datetime not null
#
class ShoppingCartItem < ActiveRecord::Base
attr_accessible :owner_id, :owner_type, :quantity, :item_id, :item_type, :price
acts_as_shopping_cart_item
end
Can anyone help me what I am missing here?
hope u are aware that
Rails 3
As of Version 0.2.0 Rails 3 is no longer supported. Please use the 0-1-x branch if you still need to implement this gem in a Rails 3 app
gem 'acts_as_shopping_cart', :github => 'crowdint/acts_as_shopping_cart', :branch => '0-1-x'
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
undefined method `to_f' for #<ActiveRecord::Relation:0x472d0a0>
I'm trying to make a call tracking application to learn twilio and rails.
Right now, I would like to make a graph that shows a user how many phone calls a particular phone number gets per day.
The schema is user has_many phones has_many calls.
I try to make the graph by creating an instance method that counts the number of phones on a particular day, but when I try executing the code, I get the error :
SQLite3::SQLException: no such column: calls.placed_at: SELECT COUNT(*) FROM "calls" WHERE "calls"."phone_id" = 44 AND ("calls"."placed_at" BETWEEN '2012-09-15 00:00:00.000000' AND '2012-09-15 23:59:59.999999')
I don't quite understand the code I'm using for the instance method, and it's probably calling the wrong column. Your help on this would be greatly appreciated.
Here's the important part of my call model:
def total_on(date)
calls.where(placed_at: date.beginning_of_day..date.end_of_day).count
end
Here's how I'm counting the phone calls in my show view
<%= (1.month.ago.to_date..Date.today).map { |date| #phone.total_on(date).to_f}.inspect %>
Here's how I define the #phone variable
#phone = Phone.find_by_id(params[:id])
Here's my complete phone model (for schema reference)
# == Schema Information
#
# Table name: phones
#
# id :integer not null, primary key
# name :string(255)
# twilio_number :integer
# original_number :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Phone < ActiveRecord::Base
attr_accessible :original_number, :user_id, :name, :twilio_number
belongs_to :user
has_many :calls, dependent: :destroy
validates :name, presence: true
validates :twilio_number, presence: true
validates :original_number, presence: true
validates :user_id, presence: true
default_scope order: 'phones.created_at DESC'
validate :check_phone_limit, :on => :create
def check_phone_limit
if User.find(self.user_id).at_max_phone_limit?
self.errors[:base] << "Cannot add any more phones"
end
end
def original_number=(value)
num = value.to_s.gsub(/[^0-9+]/, "")
write_attribute(:original_number, num.to_i)
end
def total_on(date)
calls.where(placed_at: date.beginning_of_day..date.end_of_day).count
end
end
Here's my complete call model
# == Schema Information
#
# Table name: calls
#
# id :integer not null, primary key
# AccountSid :string(255)
# From :string(255)
# To :string(255)
# CallStatus :string(255)
# ApiVersion :string(255)
# Direction :string(255)
# FromCity :string(255)
# FromState :string(255)
# FromZip :string(255)
# FromCountry :string(255)
# ToCity :string(255)
# ToState :string(255)
# ToZip :string(255)
# ToCountry :string(255)
# CallSid :string(255)
# DialCallSid :string(255)
# DialCallDuration :string(255)
# DialCallStatus :string(255)
# RecordingUrl :string(255)
# phone_id :integer
# DialCallMinutes :integer
# created_at :datetime
# updated_at :datetime
#
class Call < ActiveRecord::Base
attr_accessible :AccountSid, :From, :To, :CallStatus, :ApiVersion, :Direction, :FromCity, :FromState, :FromZip, :FromCountry, :ToCity, :ToState, :ToZip, :ToCountry, :CallSid, :DialCallSid, :DialCallDuration, :DialCallStatus, :RecordingUrl, :DialCallMinutes
belongs_to :phone
def self.create_from_incoming_call(params)
user_phone = Phone.find_by_twilio_number(params['To']) #Finds the phone number in the database based on what phone Twilio is calling
twilio_request_params = {
:CallSid => params['CallSid'],
:AccountSid => params['AccountSid'],
:From => params['From'],
:To => params['To'],
:CallStatus => params['CallStatus'],
:ApiVersion => params['ApiVersion'],
:Direction => params['Direction'],
:FromCity => params['FromCity'],
:FromState => params['FromState'],
:FromZip => params['FromZip'],
:FromCountry => params['FromCountry'],
:ToCity => params['ToCity'],
:ToState => params['ToState'],
:ToZip => params['ToZip'],
:ToCountry => params['ToCountry']
:phone_id => user_phone.phone_id
}
call = Call.new(twilio_request_params)
call.save
return call
end
def Call.update_dial_call(params)
twilio_request_params = {
:DialCallSid => params['DialCallSid'],
:DialCallDuration => params['DialCallDuration'],
:DialCallStatus => params['DialCallStatus'],
:RecordingUrl => params['RecordingUrl'],
:DialCallMinutes => (params['DialCallDuration'].to_f/60.to_f).ceil
}
call = Call.where( :CallSid => params['CallSid'] ).first
call.update_attributes twilio_request_params
call.save
end
end
I've been stuck on this for a while; any help would be greatly appreciated!
Your call model uses the standard rails created_at, yet your query was using placed_at, which doesn't exist.
What I would like to happen is every single time a new file is uploaded, user.space_used is updated.
But that doesn't happen right now. In order to get an update, I have to manually run user.update_space at the console to update a specific user, or use an array to cycle through all the users and update it like that.
How do I get it to do it at the right time - also, it would be nice if I could verify that the space_used column on the User model has the total sum of the filesizes of all the files uploaded for that user on the Upload model.
My user model looks like this:
# == Schema Information
# Schema version: 20110412170916
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# encrypted_password :string(128)
# password_salt :string(255)
# reset_password_token :string(255)
# remember_token :string(255)
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# username :string(255)
# first_name :string(255)
# last_name :string(255)
# created_at :datetime
# updated_at :datetime
# invitation_token :string(60)
# invitation_sent_at :datetime
# plan_id :integer
# current_state :string(255)
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# space_used :integer default(0), not null
# failed_attempts :integer default(0)
# unlock_token :string(255)
# locked_at :datetime
# trial_end_date :date
# active_subscription :boolean
#
class User < ActiveRecord::Base
acts_as_voter
devise :database_authenticatable, :confirmable, :registerable, :timeoutable,
:recoverable, :rememberable, :trackable, :validatable, :invitable, :lockable
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :first_name, :last_name, :plan_id
after_save :update_space
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
def update_space
total_size = 0
if self.uploads.count > 0
self.uploads.each do |upload|
total_size += upload[:image_file_size]
end
end
self.space_used = total_size
end
def space_threshold_reached?
self.plan.storage == self.space_used
end
def space_left
(self.plan.storage * 1024 * 1024 * 1024) - self.space_used.to_f
end
end
My Upload model looks like this:
# == Schema Information
# Schema version: 20110330215959
#
# Table name: uploads
#
# id :integer not null, primary key
# name :string(255)
# description :string(255)
# image_file_name :string(255)
# image_content_type :string(255)
# image_file_size :integer
# image_updated_at :datetime
# stage_id :integer
# user_id :integer
# created_at :datetime
# updated_at :datetime
class Upload < ActiveRecord::Base
acts_as_voteable
has_attached_file :image, :styles => {
:thumb => "64x64" },
:storage => :s3,
:path => "/:style/:id/:filename"
validates_attachment_presence :image
validates_attachment_size :image, :less_than => 10.megabytes
validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/JPG']
after_post_process :update_users_space_used
def self.total_used
total_size = 0
all.each do |upload|
total_size += upload.image_file_size
end
return total_size
end
def update_users_space_used
Authorization.current_user.space_used += self.image_file_size
end
end
Thanks.
Edit1: Btw, I am using paperclip to manage the uploads.
Edit2: In the Upload.rb model, I changed the before_save to the after_post_process callback for paperclip and it still doesn't work.
Seems like Paperclip's after_post_process callback would be what you want.
I have a Rails app that has "Datapoint" and "Dataset" model objects. Datasets belog to Datapoints.
models/dataset.rb:
# Table name: datasets
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime
# updated_at :datetime
class Dataset < ActiveRecord::Base
belongs_to :user
validates :name, :presence => true
end
models/datapoint.rb:
# Table name: datapoints
#
# id :integer not null, primary key
# dataset :integer
# date :date
# value :float
# created_at :datetime
# updated_at :datetime
class Datapoint < ActiveRecord::Base
belongs_to :dataset
validates :date, :presence => true
validates :dataset, :presence => true
validates :value, :presence => true
end
My controllers/datapoints_controller.rb successfully saves datapoints records:
class DatapointsController < ApplicationController
def create
#datapoint = Datapoint.new(params[:datapoint])
#datapoint.dataset = Dataset.find(current_user.dataset)
if #datapoint.save
redirect_to root_path
else
end
end
end
However, when I look in my database, the dataset field for each datapoint entry (which is a required foreign key) is empty. How is this possible?
Looks like a bad migration (wrong field name for foreign key):
# Table name: datapoints
# dataset :integer <<<< This should be dataset_id
# date :date
...
This is the error I get:
ContactPostalcardsController#skip (NoMethodError) "undefined method `status=' for #<ContactPostalcard:0x2b21433d64b0>"
This is the code calling it and trying to assign a value to the status attribute for ContactPostalcard (the Model):
def skip
#contact_postalcard = ContactPostalcard.new(params[:contact_postalcard])
#contact_postalcard.contact_id = params[:contact_id]
#contact_postalcard.postalcard_id = params[:postalcard_id]
#contact_postalcard.status = "skipped"
#contact_postalcard.date_sent = Date.today
#contact_postalcard.date_created = Date.today
if #contact_postalcard.save
render :text => 'This email was skipped!'
end
end
This is the Model referred. Note the "annotate" output shows status as an attribute:
class ContactPostalcard < ActiveRecord::Base
attr_accessible :title, :contact_id, :postal_id, :postalcard_id, :message, :campaign_id, :date_sent, :status
belongs_to :contact
belongs_to :postalcard
alias_attribute :body, :message
alias_attribute :subject, :title
named_scope :nosugar, :conditions => { :sugarcrm => false }
def company_name
contact = Contact.find_by_id(self.contact_id)
return contact.company_name
end
def asset
Postalcard.find_by_id(self.postalcard_id)
end
def asset_class
Postalcard.find_by_id(self.postalcard_id).class.name
end
end
# == Schema Information
#
# Table name: contact_postalcards
#
# id :integer not null, primary key
# title :string(255)
# contact_id :integer
# postalcard_id :integer
# message :text
# campaign_id :integer
# date_sent :datetime
# created_at :datetime
# updated_at :datetime
# postal_id :integer
# sugarcrm :boolean default(FALSE)
# status :string(255)
#
I am unclear as to why I keep getting an 'undefined method' -- I have added the status attribute (it had been missing before but used a migration and then raked), so need some help...thank you.
Have you restarted your Rails application since you ran your migration? If you're running in production mode, Rails caches your classes until you restart it, and since status wasn't an attribute before the migration, Rails wouldn't have added accessor methods for it, which would explain why status= is undefined.