I have generated scaffold for a author and I want to add an email address to the table.
I have added author.email in my tags and it wants me to define a method. what method should i define for email and where? is it in the authors controller.
thanks
In your case email is a field for the author. You should add it to your database migration, rerun the rake db:migrare and it'll be accessible as author.email
Also, make sure to add :email to the attr_accessible list in your author model.
I think you got it incorrectly. As i believe you receiving error call " undefined method or variable call email" isn't it??
If so that means you need to add email field to the database table table you can do that by following commands
ruby script/generate migration AddEmailToAuthor email:string
rake db:migrate
now you can run your program
Related
I have got Devise setup in my rails app with my model called auth_user instead of user. I have tried accessing the currently logged in user's email address (a field called email) for me to use in a query against an Employee model like so
#employee = Employee.find_by_Email(current_auth_user.email)
but get the error:
undefined method `email' for nil:NilClass
Any ideas on how to resolve this issue?
Thanks
Paul
** EDIT **
Fix as suggested by #theButler in the comments. Resolution was to add
before_filter :authenticate_auth_user!
To the top of the class.
I'm trying different blogs with examples of Rails 3 and RSpec. Yes it's on Windows, so the answer isn't not using Windows. No choice in that. Moving on...
I am able to run the spec either with rspec spec or rake spec:models so that seems fine. However if I try to use a before block with attributes it fails on creating a Person class with those attributes. The other tests are just there to show spec can run.
Made a Person model then updated the spec
\myapp\spec\models\person_spec.rb
require 'spec_helper'
describe Person do
before(:each) do
#valid_attributes = {
:first_name => "Foo",
:last_name => "Bar"
}
end
it "should create a new instance given valid attributes" do
Person.create!(#valid_attributes)
end
it "can be instantiated" do
Person.new.should be_an_instance_of(Person)
end
it "can be saved successfully" do
Person.create.should be_persisted
end
#pending "add some examples to (or delete) #{__FILE__}"
end
Here's the output of rake spec:models command
C:\Users\laptop\Documents\Sites\myapp>rake spec:models
C:/Ruby193/bin/ruby.exe -S rspec ./spec/models/person_spec.rb
Person
←[31m should create a new instance given valid attributes (FAILED - 1)←[0m
←[32m can be instantiated←[0m
←[32m can be saved successfully←[0m
Failures:
1) Person should create a new instance given valid attributes
←[31mFailure/Error:←[0m ←[31mPerson.create!(#valid_attributes)←[0m
←[31mActiveRecord::UnknownAttributeError:←[0m
←[31munknown attribute: first_name←[0m
←[36m # ./spec/models/person_spec.rb:13:in `block (2 levels) in <top (required)>'←[0m
Finished in 0.074 seconds
←[31m3 examples, 1 failure←[0m
Failed examples:
←[31mrspec ./spec/models/person_spec.rb:12←[0m ←[36m# Person should create a new instance given valid attributes←[0m
rake aborted!
C:/Ruby193/bin/ruby.exe -S rspec ./spec/models/person_spec.rb failed
So two out of three passed just not the one with attributes.
Anything in particular that would need to be setup for a before block to run or how are attributes passed in a test with Rails 3?
Also is there a way to get rid of those ]31m and such printouts for each spec line?
Thanks
It would appear from the error that ActiveRecord can't find the attribute :first_name that you are passing as part of #valid_attributes. That is, the problem isn't with how you are using RSpec, but with the attributes you are expecting a valid model to contain.
Check that you have a :first_name field or attribute on the Person model - and verify the exact spelling (:first_name vs :firstname or some other variation)
I should update this with the answer.
The Person model did in fact contain first_name and last_name but as noted by two people above the error I was receiving pointed to ActiveRecord not finding it.
In Windows, running rake db:migrate two or three times eventually fixed it even though it wasn't missing in the model.
If you're stuck on Windows dev, this may be a good thing to know!
I finally was able to put Lubuntu on a VirtualBox on Windows 7 and it ran fine and since then I have proceeded with other examples from there.
Cheers
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.
When running my tests I get this error:
FixtureClassNotFound: No class attached to find
What causes this error and how to fix it?
Most likely this happens because a custom table name is used for a Model (using the set_table_name) or the model is in a module.
To solve, you need to add a set_fixture_class line in the test_helper.rb before the fixtures :all line:
class ActiveSupport::TestCase
self.use_transactional_fixtures = true
.
.
.
set_fixture_class my_table_name: MyModule::MyClass
fixtures :all
end
In this case the fixtures file should be called my_table_name.yml
NOTE: It would be helpful if you included the stack trace and the full error message.
In your test/test_helper.rb class, there is a line like
fixtures :all
This tells the framework to look in the directory test/fixtures and try to load each of the YAML files that it sees there and then save them to the DB. So my hunch is that you have a file in there that does not have class in app/models with the singularized name. In other words, if there is a file test/fixtures/posts.yml, then when you run your tests, the framework will look for a class named Post to load your data in.
So the first thing I would do is check to see if you have a fixture file that is not associated with one of your model classes (maybe you deleted a model but forgot to delete the fixture?)
If that doesn't work, try changing the line in your test helper to explicitly load the fixtures you need. So if you only want to load fixtures for an object named Post and an object named User, you will change:
fixtures :all
to
fixtures :posts, :users
in test_helper.rb and you should see the error go away (although other errors may now appear because your fixtures are not loaded.0
In the Event that the Class is an irregular class in terms of naming such as fish, sms
it could have been created by using the --force-plural flag
i.e
rails g model sms --force-plural
in that case you would set up an inflection which is set up under
config/initializers/inflections.rb
an example of such is this
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.plural /^(ox)$/i, '\1en'
inflect.singular /^(ox)en/i, '\1'
inflect.irregular 'person', 'people'
inflect.uncountable %w( fish sheep )
end
In this way the class can be recognized as you declared it
I got this error when I made a mistake generating some scaffold code. I used a plural model name, and that just confused the fixture loading, I guess. Regenerating the scaffold with a singular model name fixed the problem.
I have been working with Rails 3.0.5 and Ruby 1.9.2 and I have noticed that a new record doesn't get saved or isn't available for use instantly.
For example
def create
#some_record = Pool.new(params[:pool])
#some_record.users.push(current_user)
if params[:commit] == "Add More"
#some_record.save
#some_record.do_something
elsif params[:commit] == "Save"
do_something_else(params)
elsif params[:commit] == 'Cancel'
redirect_to user_url(current_user)
end
redirect_to some_other_url(current_user)
end
So when I save the record and call some_record.do_something the saved object isn't available instantly. current_user.some_records doesn't contain the newly added record but current_user.some_records.all displays the newly saved record. However on the console I am able to view the newly created record with current_user.some_records.
I'm sure I am missing something fundamental to Rails 3. I have also tried the same with current_user.some_records.build(params[:some_record] and I have the same problem. Does Rails 3 save the object instantly or is there some kind of delayed write/save because the same problem does not occur with Rails 3.0.3.
Also I am not using an authentication plugin like authlogic/devise and I simply save the current_user object to the session. I am not sure what I am doing wrong. WOuld appreciate any help?
Its also a many-to-many association between some_record and users
current_user.some_records
does not contain the newly added record because you did not save the operation after assigning #some_record.users.push(current_user).
All you have to do is to add .save after the assignment and it should work.
The model structure is not clear from your question but let's assumed that current_user belongs_to some_records
To force a database read try this:
current_user.some_records(true)
By default forcereload = false, to override this you should pass true