开发者

Manual set created_at property [Rails 3]

开发者 https://www.devze.com 2023-01-27 13:29 出处:网络
Trying to set the created_at date manually: entry = Entry.new entry.text = tweet[\'text\'] entry.source = \'tweet\'

Trying to set the created_at date manually:

entry = Entry.new
entry.text = tweet['text']
entry.source = 'tweet'
entry.user_id = user.id
entry.latitude = coords[1]
entry.longitud开发者_如何学编程e = coords[0]
entry.created_at = Chromium(tweet.created_at)

Getting the following error:

 undefined method `created_at' for #<Hash:0x1036af910>

How can I avoid this? I would like to keep created_at's default functionality as not all entries are entered in this way.


Your problem isn't with the created_at method of the ActiveRecord object. I think what's spitting the error here is actually the created_at method being called on your tweet object.

See above - you use

entry.text = tweet['text']

(tweet is a hash)... but then

entry.created_at = Chromium(tweet.created_at)

complains that the Hash doesn't have a method called created_at

 undefined method `created_at' for #<Hash:0x1036af910>


The problem here is that there isn't a created_at method on the tweet object, which is a Hash. You probably meant

entry.created_at = Chromium(tweet['created_at'])

However, when an object is saved for the first time, Rails will override the created_at attribute. This is a pretty fixed behaviour and you won't be able to override it without messing something else up.

Better to create a new datetime column, for example tweeted_at and use that.

0

精彩评论

暂无评论...
验证码 换一张
取 消