在Rails中连接表

时间:2010-09-24 08:02:33

标签: ruby-on-rails

表城市模型

class TableCity < ActiveRecord::Base
  has_many :near_cities, :foreign_key => "nearcity_id"  
end

近城模型

class NearCity < ActiveRecord::Base
  belongs_to :table_city
end

控制器

@table_cities = TableCity.find(:all, :conditions=>{:state => params[:gm], :language => params[:sp]}, :include => :near_cities)

查看

<% @table_cities.each do |table_city| %>
  <%= table_city.name %>
  <% table_city.near_cities.each do |city| %>        
    <%= city.text %>
  <% end %>   
<% end %>   

这不行,请给我一些建议。

2 个答案:

答案 0 :(得分:2)

你们的关系看起来很奇怪。 NearCity属于TableCity因此,您应该将TableCity的外键存储在near_cities表中。要实现此目的,请确保您的near_cities表格中有一个名为table_city_id的列。

您的模型可以简单地:

class TableCity < ActiveRecord::Base
  has_many :near_cities  
end

class NearCity < ActiveRecord::Base
  belongs_to :table_city
end

答案 1 :(得分:0)

在你的模特中

class TableCity < ActiveRecord::Base
  has_many :near_cities  
end

class NearCity < ActiveRecord::Base
  belongs_to :table_city
end

在您的迁移中

class CreateTableCities < ActiveRecord::Migration
  def self.up
    create_table :table_cities do |t|
      t.string :name
      t.timestamps
    end
  end

  def self.down
    drop_table :table_cities
  end
end

class CreateNearCities < ActiveRecord::Migration
  def self.up
    create_table :near_cities do |t|
      t.string :name
      t.references :table_city
      t.timestamps
    end
  end

  def self.down
    drop_table :near_cities
  end
end

最后在你的控制器中你可以做到这一点

@table_city = TableCity.find(params[:id]) #one TableCity
@near_cities = @table_city.near_cities    # all near_cities associated with the TableCity