undefined method `save' for 1:Fixnum [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I made some variables that is related to models and I want to save the new variable relating to the control structure, but I can't. It said "NoMethodError - undefined method `save' for 1:Fixnum:".
What I want to make is that the function if This program get 4 people, It will show the member name for that members. 5th member will be in the next group.
Anyone can solve this?
or if you need more information, please let me know.
Thanks
This is Waitinglists_controller
class WaitinglistsController < ApplicationController
before_action :authenticate
def new
#waitinglist = current_user.created_waitinglists.build
end
def create
#waitinglist = current_user.created_waitinglists.build(waitinglist_params)
if #waitinglist.save
redirect_to waitinglist_waiting_path(#waitinglist, #owner)
else
render :new
end
end
def waiting
#group_number = Waitinglist.select(:count_number).last
#already_group_people = Waitinglist.where(count_number: #group_number).count
#current_person_group_number = current_user.created_waitinglists.select(:count_number)
#current_group_people = Waitinglist.where(count_number: #current_person_group_number).count
case #already_group_people
when 0
#current_person_group_number = 1
#current_person_group_number.save
when 1..2
#current_person_group_number = #group_number
#current_person_group_number.save
when 3
#current_person_group_number = #group_number
#current_person_group_number.save 
redirect_to show_waitinglist_path
when 4
group_number += 1
#current_person_group_number = #group_number
#current_person_group_number.save
end
end
def show
#current_person_group_number = current_user.created_waitinglist.select(:count_number)
#matched_people = Waitinglist.find(count_number: #current_person_group_number)
#matched_people == 0 if #matched_people = nil
end
private
def created_by?(user)
return false unless user
owner_id == user.id
end
def waitinglist_params
params.require(:waitinglist).permit(:look_like, :id)
end
end
This is Sessions controller for User loggin
class SessionsController < ApplicationController
def create
user = User.find_or_create_from_auth_hash(request.env['omniauth.auth'])
session[:user_id] = user.id
redirect_to root_path
end
def destroy
reset_session
redirect_to root_path
end
end
Application contrtoller is this
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user, :logged_in?
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def logged_in?
!!session[:user_id]
end
def authenticate
return if logged_in?
redirect_to root_path
end
end
Under codes are for models
class Waitinglist < ActiveRecord::Base
belongs_to :waiting_person, class_name: 'User'
after_initialize :init
def init
self.count_number ||= 1 #will set the default value only if it's nil
end
end
class User < ActiveRecord::Base
has_many :created_waitinglists, class_name: 'Waitinglist', foreign_key: :owner_id
def self.find_or_create_from_auth_hash(auth_hash)
provider = auth_hash[:provider]
uid = auth_hash[:uid]
name = auth_hash[:info][:name]
image_url = auth_hash[:info][:image]
User.find_or_create_by(provider: provider, uid: uid) do |user|
user.nickname = name
user.image_url = image_url
end
end
end

It's quite clear to me. You call save on #current_person_group_number, which is instance of Fixnum, so it doesn't have save method defined.

Unfortunately the code you wrote makes very little sense and it is pretty hard to understand what you're trying to do here.
Firstly, you overuse instance variables. If you're not gona use them in another methods (it is hard to say as you haven't post rest of your class)
Secondly, you overuse select method.
#group_number = Waitinglist.select(:count_number).last
All it does is changing the SELECT statement when querying the database for models, but it still returns the model, not a number or field value. So #group_number is not a number - it is a WaitingList instance. If you want a number do:
group_number = WaitingList.last.count_number
(posting now as question may be closed in a second. Will update later if that won't happen)
You can only save the ActiveRecord objects, which means you need to have it somewhere. Apparantly you want to update #current_person_group_number, however you can't reassign this variable to do the trick. You have to get the whole model, change its attribute and then save the model. It would look sth like:
current_waiting_list = current_user.created_waitinglists.last # This seems to be a collection, you need to tell here which waiting list you want to get from this collection
current_waiting_list.count_number += 1
current_waitin_list.save
My last point is - please look into act_as_list gem. Since you're creating waiting list it is a must have gem for you.

Related

NameError when assigning instance of model to reference property

I'm unable to assign a model instance to a reference property of another model. Relevant code is below:
module Blog::Models
class Post < Base; belongs_to :user, dependent: :destroy end
class User < Base; has_many :posts end
...
class BasicFields < V 1.0
def self.up
create_table User.table_name do |t|
...
end
create_table Post.table_name do |t|
...
t.references :user
end
end
...
end
end
module Blog::Controllers
...
class PostEditN
...
def post(post_num)
#post = Post.find(post_num)
#user = User.find(#input.user)
...
#post.user = #user # Error thrown: NameError at /post/edit/1 uninitialized constant User
# #post.user_id = #user.id << This is my currently working solution
#post.save
redirect PostN, post_num
end
end
...
end
...
When I assign something to #post.user using Camping in console mode, it is successful, but I can't seem to accomplish the same behavior in the controller otherwise. I made do by simply assigning the #user.id to the user_id property of the Post instance. However, I would like to figure out why the alternate method works in the Camping console and not when I'm simply running the webserver.
My best guess is that this is a problem with namespaces. In the code you show Useris actually Blog::Models::User. In your controller the context is Blog::Controllers. Have you tried changing the code in the controller to?
#post = Blog::Models::Post.find(post_num)
#user = Blog::Models::User.find(#input.user)
...
I was able to resolve my issue. Seems when I was creating new Post records, I was not initializing the User. Thus, when assigning #post.user it would complain that the user property was uninitialized. The only problem I see is that an operation was attempted to be made on an oprhan Post record, which is invalid data according to the relationship with User.

Rails 4 strong parameters ActiveModel::ForbiddenAttributesError

For some reason in my current controller I am getting ActiveModel::ForbiddenAttributesError even though I believe I am using strong parameters just fine. Albeit I am using permit! for the time being to permit all model attributes. See code below, what am I missing
class HeuristicsController < ApplicationController
def index
#heuristics = Heuristic.order(:name).page params[:page]
#heuristic = Heuristic.new
end
def create
#heuristic = Heuristic.new(params[:heuristic])
if #heuristic.save
redirect_to action: 'index', :flash => {:success => "New heuristic created!" }
else
render 'new'
end
end
def new
#title = "Heuristic"
#heuristic = Heuristic.new
end
private
def heuristic_params
params.require(:heuristic).permit!
end
end
i think you did not fully understand the way that strong-params work...
you have a method
def heuristic_params
params.require(:heuristic).permit!
end
and you are not using it
Heuristic.new(params[:heuristic])

Best way to Map data?

I wanna map some data from facebook into my User class. I read now some articles about inheritance, extending, including and so on. But maybe I understand something wrong.
Is this the right approach for DataMapping in Ruby?
class User
attr_accessible :name, :address
def map_facebook
FacebookUserMapper.new(facebook_object, self)
end
end
class FacebookUserMapper
def initialize(facebook_user, user)
#facebook_user = facebook_user
#user = user
mapit
end
def self.map_it()
username
address
return #user
end
def username
#user.username = #facebook_user.name
end
def address
#user.address = #facebook_user.address
end
end
I would do like this:
def mapFacebook
FacebookUserMapper.new(facebook_object, self).call
end
class FacebookUserMapper
def initialize(facebook_user, user)
#facebook_user = facebook_user
#user = user
end
def call
username
address
self
end
# ...
end
FYI: Don't add () around methods in Ruby
The better way to map the facebook object on to your user model would be this
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
auth is the facebook object here.
tap just allows you do do something with an object inside of a block, and always have that block return the object itself.
This is a code snippet from a Railscasts episode from which you could get even more help for your facebook related app.

Passing Form Params to Model in Rails3

I'm trying to pass some parameters (count) from a form to a model.
The model basically creates a user X times.
In our form, we have this:
= f.text_field :count
And I can see this is submitted properly in the dev. log:
user"=>{"count"=>"2"}
I've tried this in my controller:
#user = User.generate(params[:count])
Generate is then supposed to call this in my user model:
def self.generate(count=10)
count.times do
.....
end
I basically need the '10' replaced with the count from form.
How can I go about this?
-- UPDATE 1 --
I've edited as below but get had to change from count to usercount because I think that's reserved in rails..
I have this in my controller:
#user = User.generate(params[:user][:usercount])
This in my user.rb:
attr_accessor :usercount
def self.generate
usercount.times do
...
end
When I submit, I get this:
ArgumentError (wrong number of arguments (1 for 0)):
app/models/user.rb:22:in `generate'
app/controllers/users_controller.rb:38:in `new_users_create'
Really frustrating...
class User
attr_accessor :count
end
#user = User.generate(params[:user][:count])
should work fine.

Testing before_create method in rspec and rails 3

I've looked into some tutes and all I saw were old posts on how to test before_create. Also it seems like they're all just testing that before_create was called i.e.:
#user = User.new
#user.should_receive(:method_name_called_by_before_create)
#user.send(:before_create) (sometimes they just do #user.save)
I want to actually test that my method worked and that it had assigned(and saved the variables) after creating the record.
Here are my models:
user.rb
class User < ActiveRecord::Base
has_one :character, :dependent => :destroy
after_create :generate_character
private
def generate_character
self.create_character(:name => "#{email}'s avatar")
end
end
and character.rb
class Character < ActiveRecord::Base
belongs_to :user
before_create :generate_character
private
def generate_character
response = api_call
#API CALL HERE
#set object attributes here
self.stat1 = calculate_stat1(response) + 5
self.stat2 = calculate_stat2(response) + 5
self.stat3 = calculate_stat3(response) + 5
end
def api_call
return api_call_response
end
end
I want to test that generate character indeed set the attributes without going online and calling the API call. Is this possible with rspec? I have a fixture of a json response so I was hoping I can stub out generate character and then use the fake response for testing.
Here's my character.spec:
describe Character do
before(:each) do
Character.any_instance.stub!(:api_call).and_return(fake_response.read)
#user = Factory(:user)
#character = #user.character
puts #character.inspect
end
def fake_response
File.open("spec/fixtures/api_response.json")
end
It prints out only 5 for each of the character's stats. Also I did a puts response in the generate_character method in character.rb and it still prints out the "real" api call.
I managed to do a puts in fake_response and it does goes through there but it also goes through the "real" api_call after, which makes the stub obsolete. How do I get through this?
A good approach here is extracting your api call into a self contained method. Something like this:
class Character < ActiveRecord::Base
belongs_to :user
before_create :generate_character
private
def generate_character
data = api_call
#set object attributes from data
end
def api_call
# returns a data structure
# resulting from the call
end
end
Then use RSpec's any_instance to stub the api_call method to return a fixed data structure
Character.any_instance.stub!(:api_call).and_return { {:id => 1, :attribute_one => "foo"} }
#user = User.create
#user.character.attribute_one.should == "foo"
for more info on any_instance check this commit

Resources