I run:
$ rails g scaffold User first_name:string last_name:string email:string website:string nodes:array links:array --orm=mongo_mapper
and get:
invoke mongo_mapper
create app/models/user.rb
(erb):1:in `template': undefined method `module_namespacing' for #<MongoMapper::Generators::ModelGenerator:0x000000035cd4a8> (NoMethodError)
...
from /home/thrive/.rvm/gems/ruby-1.9.2-p290#mlrepo/gems/mongo_mapper-0.11.1/lib/rails/generators/mongo_mapper/model/model_generator.rb:17:in `create_model_file'
...
full error output ... anyone know whats going on here?
I mean its a .rb file with what looks to be ERB code in it:
<%= module_namespacing do - %>
Error causing files:
model_generator.rb
model.rb
It looks like the edge branch called 'generator-parent-option' will do the trick:
#/Gemfile
gem 'mongo_mapper', :git => 'git://github.com/bearded/mongomapper.git', :branch => 'generator-parent-option'
I ran:
$ rails g scaffold User first_name:string last_name:string email:string website:string nodes:array links:array --skip-migration --orm=mongo_mapper
and got nice clean output:
thrive#thrive-laptop:~/rails_projects/hive$ rails g scaffold User first_name:string last_name:string email:string website:string nodes:array links:array --skip-migration --orm=mongo_mapper
invoke mongo_mapper
conflict app/models/user.rb
Overwrite /home/thrive/rails_projects/hive/app/models/user.rb? (enter "h" for help) [Ynaqdh] h
Y - yes, overwrite
n - no, do not overwrite
a - all, overwrite this and all others
q - quit, abort
d - diff, show the differences between the old and the new
h - help, show this help
Overwrite /home/thrive/rails_projects/hive/app/models/user.rb? (enter "h" for help) [Ynaqdh] Y
force app/models/user.rb
invoke test_unit
create test/unit/user_test.rb
create test/fixtures/users.yml
route resources :users
invoke scaffold_controller
identical app/controllers/users_controller.rb
invoke haml
exist app/views/users
identical app/views/users/index.html.haml
identical app/views/users/edit.html.haml
identical app/views/users/show.html.haml
identical app/views/users/new.html.haml
identical app/views/users/_form.html.haml
invoke test_unit
identical test/functional/users_controller_test.rb
invoke helper
identical app/helpers/users_helper.rb
invoke test_unit
identical test/unit/helpers/users_helper_test.rb
invoke stylesheets
identical public/stylesheets/scaffold.css
Related
I am a beginner in Ruby on Rails and following the below article:-
http://guides.rubyonrails.org/migrations.html
If I need to generate a migration and a model, I can use, for example :-
$ rails generate model Product name:string description:text
and that would create :-
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
However, If I have a bigger model (with many properties). I don't want to put all the properties in the "rails generate" command. Can I hand code the model first and then generate the migration from that model file?
Sorry for asking so stupid question. I am just trying to understand.
Generate command is not must to do thing. It's just a script which helps you to automate some job. What exactly this command has done you can see in console after running generate command. It looks like this:
rails generate scaffold User name:string email:string
invoke active_record
create
db/migrate/20100615004000_create_users.rb
create
app/models/user.rb
invoke
test_unit
create
test/unit/user_test.rb
create
test/fixtures/users.yml
route resources :users
invoke scaffold_controller
create
app/controllers/users_controller.rb
invoke
erb
create
app/views/users
create
app/views/users/index.html.erb
create
app/views/users/edit.html.erb
create
app/views/users/show.html.erb
create
app/views/users/new.html.erb
create
app/views/users/_form.html.erb
invoke
test_unit
create
test/functional/users_controller_test.rb
invoke
helper
create
app/helpers/users_helper.rb
invoke
test_unit
create
test/unit/helpers/users_helper_test.rb
invoke stylesheets
converted by Web2PDFConvert.com
create
public/stylesheets/scaffold.css
You can actually create/modify all files by your hand. But the benefit of using generate is that it automatically invokes all necessary plugins and etc to generate all required files.
That's why it's recommended to use generate command even for very complicated models, controllers and etc.
So in your case I would suggest to divide the building the model in several steps. It could be like this:
rails generate model Product name:string description:text
rails generate migration AddPriceToProducts price:integer
rails generate migration AddDiscountToProducts discount:integer
and so on
Every step you could rollback in case if you made some mistake and it helps you to not harm
your database.
You can hand-code the migration. The model's attributes are read directly from the database... so if you add t.string :name to the migration file, and then run rake db:migrate, that column will be added to the table, therefore making it available as an attribute on your model.
In rails 2 I had a lib/migration_helpers.rb file with methods for setting and dropping foreign keys in the db.
These methods were available in self.up and self.down in migration files by adding in the migration file
require 'migration_helpers'
at the top, and
extend MigrationHelpers
immediately after the class statement.
In rails 3 this does not work, and if i try to run a migration using set_foreign_key method from migration_helpers.rb the following error is thrown:
== AddFkToArticles: migrating ================================================
-- set_foreign_key("articles", "book_id", "books")
rake aborted!
An error has occurred, this and all later migrations canceled:
undefined method `set_foreign_key' for #<AddFkToArticles:0x000001034a1f38>
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
I already checked that in config/application.rb the autoload path is set to include lib.
The file is effectively required, because if i comment out the require statement then rails whines about the missing 'migration_helpers' file.
I suspect this is a scoping problem (rails 2 used "def self.up", rails 3 uses "def change")
but cannot imagine how to solve the problem (by now I simply copied the code in the migration file, just to check that it does what it should do).
Francesco
I don't know what exactly you're trying to accomplish but here's some code that might give you a clue.
## lib/test_helper.rb
module TestHelper
def my_table_name
return :mytable
end
end
And then the migration:
## db/migrate/test_migration.rb
include TestHelper
class TestMigration < ActiveRecord::Migration
def self.up
create_table my_table_name
end
def self.down
drop_table my_table_name
end
end
Including this helper inside the Migration class doesn't work so it should be outside.
I am using the rails3-amf gem by warhammerkid in my Rails 3 / Flex 4 project.
AFAIK, I have correctly followed the "Getting Started" instructions from the GitHub page.
I have added the gem lines to my Gemfile.
I have installed the gems using bundle install.
From my Flex application, I will be making the RemoteObject call to the index action in the ManageMySchool::GradesController file. This is the code in the app/controllers/manage_my_school/grades_controller.rb file:
class ManageMySchool::GradesController < ApplicationController
respond_to :html, :amf
def index
#grade = Grade.first
respond_with(#grade) do |format|
format.amf { render :amf => #grade.to_amf }
end
end
end
The name of the model which is to be serialized is called Grade in both the Rails project (app/models/Grade.rb) and the Flex project (Grade.as with a RemoteAlias set as Grade). In the config/application.rb file, I have done the class mapping this way:
config.rails3amf.class_mapping do |m|
m.map :as => 'Grade', :ruby => 'Grade'
end
And I have done a parameter mapping this way:
config.rails3amf.map_params :controller => 'ManageMySchool::GradesController', :action => 'index', :params => [:authenticity_token]
Problem
Now, when I run the server and make the RemoteObject call from Flex, I get a to_amf undefined method error for the Grade model.
If I change Grade.first to Grade.all, #grade would have an array of Grades. But the undefined method error message still mentions the Grade model. This means that the to_amf method is working for the Array class but not for the ActiveRecord model.
Why is this? What am I doing wrong?
Is there something I have to do to "enable" the rails3-amf gem for ActiveRecord models?
I would appreciate any insights. Thanks!
Update
#warhammerkid: Here is the output of Grade.ancestors as seen in rails console.
ree-1.8.7-2011.03 :006 > puts Grade.ancestors
Grade
ActiveRecord::Base
Paperclip::CallbackCompatability::Rails3::Running
Paperclip::CallbackCompatability::Rails3
Paperclip::Glue CanCan::ModelAdditions
Authlogic::ActsAsAuthentic::ValidationsScope
Authlogic::ActsAsAuthentic::SingleAccessToken
Authlogic::ActsAsAuthentic::SessionMaintenance
Authlogic::ActsAsAuthentic::RestfulAuthentication::InstanceMethods
Authlogic::ActsAsAuthentic::RestfulAuthentication
Authlogic::ActsAsAuthentic::PersistenceToken
Authlogic::ActsAsAuthentic::PerishableToken
Authlogic::ActsAsAuthentic::Password
Authlogic::ActsAsAuthentic::MagicColumns
Authlogic::ActsAsAuthentic::Login
Authlogic::ActsAsAuthentic::LoggedInStatus
Authlogic::ActsAsAuthentic::Email
Authlogic::ActsAsAuthentic::Base
ActiveRecord::Aggregations
ActiveRecord::Transactions
ActiveRecord::Reflection
ActiveRecord::Serialization
ActiveModel::Serializers::Xml
ActiveModel::Serializers::JSON
ActiveModel::Serialization
ActiveRecord::AutosaveAssociation
ActiveRecord::NestedAttributes
ActiveRecord::Associations
ActiveRecord::AssociationPreload
ActiveRecord::NamedScope
ActiveModel::Validations::Callbacks
ActiveRecord::Callbacks
ActiveModel::Observing
ActiveRecord::Timestamp
ActiveModel::MassAssignmentSecurity
ActiveRecord::AttributeMethods::Dirty
ActiveModel::Dirty
ActiveRecord::AttributeMethods::TimeZoneConversion
ActiveRecord::AttributeMethods::PrimaryKey
ActiveRecord::AttributeMethods::Read
ActiveRecord::AttributeMethods::Write
ActiveRecord::AttributeMethods::BeforeTypeCast
#<Module:0x1028356f0> ActiveRecord::AttributeMethods::Query
ActiveRecord::AttributeMethods
ActiveModel::AttributeMethods
ActiveRecord::Locking::Optimistic
ActiveRecord::Locking::Pessimistic
ActiveRecord::Validations
ActiveModel::Validations::HelperMethods
ActiveModel::Validations
ActiveSupport::Callbacks
ActiveModel::Conversion
ActiveRecord::Persistence Object
PP::ObjectMixin Base64::Deprecated
Base64
ActiveSupport::Dependencies::Loadable
Kernel
Note that only ActiveModel::Serialization is there. No mention of Rails3AMF.
Does this mean I have to do something special to load the Rails3AMF module for the ActiveRecord models?
I am using Rails 3.0.5 with the latest version of ree. The gems are all contained in a gemset managed using rvm.
Update 2
If I remove the to_amf in the render :amf line, then I get the following error:
Grade Load (0.3ms) SELECT `grades`.* FROM `grades` LIMIT 1
Completed 200 OK in 195ms (Views: 0.1ms | ActiveRecord: 0.8ms)
Sending back AMF
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.last):
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.8ms)
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (13.6ms)
Started POST "/amf" for 127.0.0.1 at Fri Apr 15 17:03:34 +0530 2011
Sending back AMF
Update 3
If I manually add the line include Rails3AMF::Serialization at the top of the Grade.rb model file, then it all works. So, does this mean that I have to put this line in all my models?
I see that this is already being done in line numbers 40 - 42 in the lib/rails3-amf/serialization.rb file of the gem:
# Hook into any object that includes ActiveModel::Serialization
module ActiveModel::Serialization
include Rails3AMF::Serialization
end
Why isn't this working? Should I force-load the gem when my application initializes or something?
Thanks!
Update 4 - Solved by this workaround
Okay, I just ended up adding this code block in an initializer:
class ActiveRecord::Base
include Rails3AMF::Serialization
end
And it is working.
#warhammerkid - Thanks for the help.
Rails3AMF::Serialization, the module that adds the to_amf method, is included in ActiveModel::Serialization when Rails3-AMF loads. If it's somehow not being included even though the code is running and ActiveModel::Serialization is one of your model's ancestors, then the simplest solution is just to add "include Rails3AMF::Serialization" at the top of your model implementation. I've never tried gem sets before, but it might be an issue with them, as everything works correctly using Bundler.
As an aside, feel free to post a bug to https://github.com/warhammerkid/rails3-amf/issues.
I'm fairly new to rails and TDD (as will no doubt be obvious from my post) and am having a hard time wrapping my brain around Rspec and FactoryGirl.
I'm using Rails 3, rspec and factory girl:
gem 'rails', '3.0.3'
# ...
gem 'rspec-rails', '~>2.4.0'
gem 'factory_girl_rails'
I have a user model that I've been successfully running tests on during development, but then needed to add an attribute to, called "source". It's for determining where the user record originally came from (local vs LDAP).
In my factories.rb file, I have several factories defined, that look something like the following:
# An alumnus account tied to LDAP
Factory.define :alumnus, :class => User do |f|
f.first_name "Mickey"
f.last_name "Mouse"
f.username "mickeymouse"
f.password "strongpassword"
f.source "directory"
end
I have a macro defined (that's been working up until now) that looks like this:
def login(user)
before(:each) do
sign_out :user
sign_in Factory.create(user)
end
end
I'm calling it in multiple specs like so (example from users_controller_spec.rb):
describe "for non-admins or managers" do
login(:alumnus)
it "should deny access" do
get :index
response.should redirect_to(destroy_user_session_path)
end
end
If I don't specify the "source" attribute, everything works OK, but as soon as I do, I get an error like so when running the test
12) UsersController for non-admins or managers should deny access
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `source=' for #<User:0x00000100e256c0>
I can access the attribute no problem from the rails console and the app itself, and it's listed in my attr_accessible in the user model. It's almost as though Rspec is seeing an old version of my model and not recognizing that I've added an attribute to it. But if I put the following line into my user model, the error disappears
attr_accessor :source
... which indicates to me that it is actually looking at the correct model.
Help!
How about running this?
rake db:test:load
[If you added a new attribute you'd need to migrate it to the test database.]
if you don't use schema.rb (e.g. you have set config.active_record.schema_format = :sql)
you should run
rake db:test:prepare
I have several controllers already set up. Now I want to start writing spec tests for them. Is there a command that generates the spec files automatically? I know rails does this for new resources, but I don't know if it does it for existing controllers/models too.
rails g rspec:controller ControllerName
When it asks you to override the existing controller, type n.
There are two options. If you want an empty spec file, you could try with:
rails g rspec:controller ControllerName
Now, if you want a spec file with initial specs for a basic REST controller, try with:
rails g rspec:scaffold ControllerName
If you've configured rspec in application.rb:
config.generators do |g|
g.test_framework :rspec
end
then rails g controller things will work. Opt not to overwrite files as they're generated.
All a spec looks like when it's generated is the following:
require 'spec_helper'
describe ThingsController do
it "should be successful" do
get :index
response.should be_successful
end
end
I often create the specs manually, as it's rather trivial.