代码之家  ›  专栏  ›  技术社区  ›  Zabba fl00r

如何在rubyonrails中使用没有控制器的模型?

  •  0
  • Zabba fl00r  · 技术社区  · 15 年前

    我有这些模型(为了简洁起见,这里没有显示迁移——它们是firstname、city等标准字段):

    class User < ActiveRecord::Base
      has_one :address
    end
    
    class Address < ActiveRecord::Base
      has_one :user
    end
    

    如何使用Address类来管理底层表数据?简单地调用它的方法?在这种情况下,如何将参数/属性值传递给类?(因为地址没有控制器(因为它是在内部使用的)。

    1 回复  |  直到 11 年前
        1
  •  0
  •   Matt Briggs    15 年前
    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
    

    还有更多的事情,如果你对我没有涉及的东西有任何问题,请告诉我