I hava a reply model:
class Reply < ActiveRecord::Base
belongs_to :topic
before_create { |record|
Topic.find(record.topic_id).update_attributes!(:last_reply_id =>
record.id)}
end
And a topic model:
class Topic < ActiveRecord::Base
has_many :replies
end
And i write a topic spec here:
…
it “should know the last reply” do
@topic.save
reply = @topic.replies.build
reply.save
reply.topic.should === @topic
@topic.last_reply_id.should == reply.id
end
…
last_reply_id is for the topic’s latest reply id, when i run the
test ,i got this :
‘Topic should know the last reply’ FAILED expected: 10,
got: nil (using ==)
spec/models/topic_spec.rb:26:
spec/models/topic_spec.rb:3:
Why i couldn’t save the last_reply_id for topic???Help me!!
On Sun, Apr 13, 2008 at 10:24 AM, Ragnarok [email protected] wrote:
end
Since you’re doing this in before_create, I don’t think that record (the
Reply instance) will have an id yet. If you switch the callback to an
after_create, does it work?
Craig
On Apr 13, 11:01 pm, “Craig D.” [email protected]
wrote:
record.id)}
end
Since you’re doing this in before_create, I don’t think that record (the
Reply instance) will have an id yet. If you switch the callback to an
after_create, does it work?
Craig
It’s the same too! i try after_create,before_save,after_save …,it
also couldn’t work!
On Sun, Apr 13, 2008 at 11:20 AM, Ragnarok [email protected] wrote:
It’s the same too! i try after_create,before_save,after_save …,it
also couldn’t work!
I played with this a little bit, but I couldn’t make it work with
callbacks.
As an alternative, to get the latest reply’s id, you could just do
@topic.replies.last.id
instead of storing last_reply_id on Topic. I think that this approach
will
rely on the sequence of IDs instead of record timestamps, but it may
suffice
for you.
Craig
On Apr 14, 3:58 am, “Craig D.” [email protected]
wrote:
instead of storing last_reply_id on Topic. I think that this approach will
rely on the sequence of IDs instead of record timestamps, but it may suffice
for you.
Craig
Thank you!i try with a virtual attribute, and it’s work !
but i couldn’t understand , why it doesn’t work with callback method!?
i want to know the reason!
Try reloading your topic model before you check the last_reply_id…
Mark
On Sun, Apr 13, 2008 at 10:24 AM, Ragnarok [email protected] wrote:
has_many :replies
it “should know the last reply” do
Why i couldn’t save the last_reply_id for topic???Help me!!
–
Mark Van H., Partner / Software Developer
[email protected], (616) 706-6842
Mutually Human Software, http://mutuallyhuman.com