如何在Ruby on Rails中使用没有控制器的模型?

时间:2010-09-15 21:34:13

标签: ruby-on-rails

我刚学习Ruby on Rails(之前没有Ruby经验) 我有这些模型(为了简洁起见,这里没有显示迁移 - 它们是标准字段,如名字,城市等):

class User < ActiveRecord::Base
  has_one :address
end

class Address < ActiveRecord::Base
  has_one :user
end

如何使用Address类来管理基础表数据?只需调用它的方法?在这种情况下,如何将params / attribute值传递给类? (因为Address不会有控制器(因为它意味着在内部使用))。 如何做这样的事情?

1 个答案:

答案 0 :(得分: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

还有更多信息,如果您对我未涵盖的内容有任何疑问,请与我联系