开发者

Connecting Tables in Rails

Table City Model

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

NearCity Model

class NearCity < ActiveRecord::Base
  belongs_to :table_city
end

Controller

@table_cities = TableCity.find(:all, :conditio开发者_如何学编程ns=>{:state => params[:gm], :language => params[:sp]}, :include => :near_cities)

View

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

This is not working, Kindly give me some suggestions.


Your relationships look strange. A NearCity belongs to a TableCity therefore, you should be storing the foreign key of the TableCity in your near_cities table. To achieve this make sure your near_cities table has a column called table_city_id.

Your models can simply be:

class TableCity < ActiveRecord::Base
  has_many :near_cities  
end

class NearCity < ActiveRecord::Base
  belongs_to :table_city
end


In your Models

class TableCity < ActiveRecord::Base
  has_many :near_cities  
end

class NearCity < ActiveRecord::Base
  belongs_to :table_city
end

In your migrations

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

And then finally in your controller you can do this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜