سؤال

2 Models => Town and Island

# Town.rb
belongs_to :player
belongs_to :island

# Island.rb
has_many :towns

The connection occurs via 2 different integer variables

:island_x 
:island_y

e.g. :island_x => 34 :island_y => 43

How can i set this association up ?


# CreateIslands
    create_table :islands, id: false do |t|
      t.primary_key :grepo_id
      t.integer :island_x
      t.integer :island_y
      t.integer :type_number
      t.integer :available_towns

      t.timestamps
    end

# CreateTowns
    create_table :towns, id: false do |t|
      t.primary_key :grepo_id
      t.integer :player_id
      t.string :name
      t.integer :island_x
      t.integer :island_y
      t.integer :slot
      t.integer :points

      t.timestamps
    end
هل كانت مفيدة؟

المحلول

Something like this

Class Town < ActiveRecord::Base

belongs_to :player
belongs_to :island ,foreign_key :island_x

end

Update

I see there is no use of island_x and island_y in both the schemas.You can just have a normal foreign_key island_id in the towns table and you can make a call town.island or island.towns.

Update1

I got it wrong with foreignn_key above.You can just make a method and make the matching like this

def some_method

@island_x = Island.find(params[:island_x])

@island_y = Island.find(params[:island_x])

@town_x = Town.where(:island_x => @island_x.id)

@town_y = Town.where(:island_y => @island_y.id)

end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top