How to add a variable to an existing model ruby on rails
Very green question here. I built a simple blog following the instructions here http://guides.rubyonrails.org/getting_started.html
How can I add another string variable to the post object?
Once I have a new variable, how do I create new posts in html.erb files? The code below gives me a NoMethodError exception for the 'email' method. How do I make this code run without an error?
btw - what is convention on stackoverflow for followup questions?
<h2>Add a post:</h2>
<%= form_for([@post, @post.actions.build]) do |f| %>
<div class="field">
<%= f.label :number_performed %><br />
<%= f.text_field :number %>
</div>
<div class="field">
<%= f.label :your_e开发者_如何学运维mail %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
At the very least to get the minimum functionality, you must add another column to your post table.
See here on how to add a column programitcally:
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
OR you can run the rails generate migration command like so:
rails generate migration AddColumnNameToPost column_name:string
No matter what route you go down, make sure you run the following to apply those migrations to your database:
rake db:migrate
From there you can access:
@post = Post.new
@post.column_name = "value"
#etc
same like answer from drharris:
rails generate migration add_newvariableone_and_newvariabletwo_to_modelpluralname newvariableone:string newvariabletwo:string
it will create ruby file inside db/migrate where the content like
class AddNewVariableOneAndNewVariableTwoToModelPluralname < ActiveRecord::Migration
def self.up
add_column :modelpluralname, :newvariableone, :string
add_column :modelpluralname, :newvariabletwo, :string
end
def self.down
remove_column :modelpluralname, :newvariableone
remove_column :modelpluralname, :newvariableone
end
end
hope this help you thanks
You should look at the section on Migrations. In your case, you would use a command like:
rails generate migration AddRandomStringToPost random_string:string
精彩评论