代码之家  ›  专栏  ›  技术社区  ›  lightalloy

在创建ActiveRecord对象时传递关联参数

  •  3
  • lightalloy  · 技术社区  · 15 年前

    在我的应用程序中,我有两个这样的类:

    class City < ActiveRecord::Base
      has_many :events
    end
    
    class Event < ActiveRecord::Base
      belongs_to :city
      attr_accessible :title, :city_id
    end
    

    如果我创建城市对象:

    city = City.create!(:name => 'My city')
    

    然后传递参数来创建这样的事件:

    event = Event.create!(:name => 'Some event', :city => city)
    

    我得到

    event.city_id => null
    

    So the question is - is it possible to pass parameters in such a way to get my objects connected, what am I doing wrong? 或者我应该用其他方法(比如

    event.city = city
    

    ) ?

    3 回复  |  直到 15 年前
        1
  •  4
  •   James A. Rosen    15 年前

    一般来说,当你有一个 attr_accessor 排除或 attr_protected 包括 :city 属性对 Event . 允许 :city_id 可接近的是 自动允许 城市 是这样的。

    (注意:这个答案是根据上述评论中的讨论提供的,因此是社区wiki。)

        2
  •  1
  •   James A. Rosen    15 年前

    这将起作用:

    city = City.create!(:name => "London")
    
    event = Event.create!(:name => "Big Event")
    event.city = city
    event.save
    

    或者,如果 Event.validates_presence_of :city 因此 Event.create! 如果没有 City 你可以这样做:

    event = Event.new(:name => 'Big Event').tap do |e|
      e.city = city
      e.save!
    end
    
        3
  •  0
  •   alex.zherdev    15 年前

    你应该这么做

    event = Event.create!(:name => 'Some event', :city_id => city.id)
    
    推荐文章