def create
msg = current_user.msgs.build(params[:msg])
msg.message = msg.message[0..140]
msg.created_at = Time.now # HACK
if msg.save
else
flash[:error] = "Your article must contain some text."
end
redirect_to root_path
end
I want to add something like
msg.title = msg.title
msg.byline = msg.byline
So that I can have a title and byline associated with each message, but if I do I get the error
NoMethodError in Home#index
Showing /Users/fred/Desktop/demosite/app/views/home/index.html.erb where line #25 raised:
undefined method `title' for #<msg:0x00000104dbcn90>
How do I add title and byline so that I do开发者_如何学Pythonnt get nomethoderrors? Thanks
First of all: what?
msg = current_user.msgs.build(params[:msg])
msg.message = msg.message[0..140]
msg.created_at = Time.now # HACK
This confuses us. Why would you:
1) Limit the message length in the controller and not as a before_save
on the model?
before_save :only_140_characters
def only_140_characters
self.message = self.message[0..140]
end
2) Set created_at
yourself in the controller? This is taken care of by Rails automatically. When a record is created, the created_at
field will be set to a value by ActiveRecord. Similarly, when you update a record updated_at
will be set to the current time as well. Rails will only do this if your fields actually exist.
Now on to the real question: Why are you getting that undefined method error?
apneadiving points out correctly in the comments you need to add a migration to add that column to the messages
table. You can do this by running this command:
rails g migration add_title_to_messages title:string
Then by running rake db:migrate
will that column be added to the messages
table in the database. Keep in mind that you'll need to run RAILS_ENV=production rake db:migrate
to add it to your production database too, if you are at that point.
精彩评论