2010-09-06 61 views
0

我是acually嘗試寫Ruby代碼的API博客建議對Ruby代碼的API

我已經寫了Ruby代碼爲

Loading development environment (Rails 2.3.8) 
    >> class Blogpost < ActiveRecord::Base 
    >> has_many :taggings 
    >> has_many :tags,:through => :taggings 
    >> end 
    => nil 
>> class Taggings < ActiveRecord::Base 
>> belongs_to :blogpost 
>> belongs_to :tag 
>> end 
=> nil 



?> @tags=Tag.find_by_name("blog7") 
=> #<Tag id: 4, name: "blog7"> 
>> @taggings=Tagging.find_by_id(@tags.id) 
=> #<Tagging id: 4, tag_id: 1, taggable_id: 4, taggable_type: "Blogpost", created_at: "2010-09-02 10:03:08"> 
>> @blogposts=Blogpost.find_by_id(@taggings.taggable_id) 
    => #<Blogpost id: 4, title: "blog post4", type: nil, slug: "blog-post4", description: "<p>BLOG desc 4</p>", meta: nil, user_id: 1, category_id: 379344121, times_viewed: 2, comments_count: 0, published: 1, created_at: "2010-09-02 10:03:08", updated_at: "2010-09-03 05:11:46", delta: false> 

無論是編寫Ruby代碼的方式是正確的程序對於API ..

請給出建議..

+0

'class taggings'是'class tagging'嗎? – OmniBus 2010-09-06 09:11:22

+0

亞它應該只是標記..我的表名是標記 – useranon 2010-09-06 09:23:04

回答

0

我不確定你在API上下文中的含義。如果你的意思是,這是定義一個ActiveRecord類的正確方法,那麼是的,你做到了。如果你的意思是,這是使用find api查找對象的最佳方式,我唯一的建議是它會默認爲id,所以find_by_id是多餘的Tagging.find @tag.id可以工作,並且通常在從控制器進行查找時它會更多很可能通過參數找到它Tagging.find params[:id]