2010-09-15 58 views
0

我只是學習Ruby on Rails的(之前沒有經驗的Ruby) 我有這些模型(不顯示在這裏爲簡潔的遷移 - 他們是標準的領域,如姓名,城市等):如何在Ruby on Rails中使用沒有控制器的模型?

class User < ActiveRecord::Base 
    has_one :address 
end 

class Address < ActiveRecord::Base 
    has_one :user 
end 

如何我是否使用Address類來管理基礎表數據?只需調用它的方法?在這種情況下,我如何將Params /屬性值傳遞給類? (因爲地址沒有控制器(因爲它意味着在內部使用))。 人們如何去做這樣的事情?

回答

0
u = User.create :first_name => 'foo', :last_name => 'bar' #saves to the database, and returns the object 
u.address.create :street => '122 street name' #saves to the database, with the user association set for you 

#you can also just new stuff up, and save when you like 
u = User.new 
u.first_name = 'foo' 
u.last_name ='bar' 
u.save 

#dynamic finders are hela-cool, you can chain stuff together however you like in the method name 
u = User.find_by_first_name_and_last_name 'foo', 'bar' 

#you also have some enumerable accessors 
u = User.all.each {|u| puts u.first_name } 

#and update works as you would expect 

u = User.first 
u.first_name = 'something new' 
u.save 

#deleting does as well 

u = User.first 
u.destroy 

有更多的東西然後就這樣,讓我知道,如果你有任何東西的問題,我沒有涵蓋

相關問題