简体   繁体   中英

How can I utilize a mix of array and hashes in Ruby on Rails Models?

me and my friend are new programmers and we are trying to create an app using Ruby on Rails that sports clubs in a small community can use to keep scores for their teams.

We have a user model and users(specifically the head of a sports club) can create a page to display the score of all the teams in the club. This page has its own model called scoreboards .

Currently, the migration for the scoreboards looks like this:

class CreateScoreboards < ActiveRecord::Migration
  def change
    create_table :scoreboards do |t|
      t.string :name_of_scoreboard
      t.string :name_of_organization
      t.string :name_of_activity
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :scoreboards, :users
    add_index :scoreboards, [:user_id, :created_at]
  end
end

Now, all those variables have a 1:1 relation with each scoreboard page instance. We want to add a teams variable to the scoreboards model . Since there would be many teams, we decided to use the following code logic:

TeamArray[]= [ hash1= {teamname: "Example", teamwins: "20", teamloss:  "10"}, 
hash2= {teamname: "Example2", teamwins: "10", teamloss:  "5"},]

So the the team data will be held in a hash, and the hash will be held in a array of all the teams for that particular scoreboard. However, we do not know how to add an array of hashes to the model. Is there a better way to do this? If this way is possible, how can we have an array of hashes associated with an an instance of the scoreboards model? Apologies in advance for any confusion.

Yes, there is a better way to do this. Scoreboard should be a model; Team should be another model. The whole point of a relational database is that it can relate different pieces of information. To do so, set up a relationship between the two: Scoreboard has_many :teams ; Team belongs_to :scoreboard (if each team can only be on one scoreboard; if they can belong to multiple scoreboards, it gets a teeny bit more complicated, look into has_and_belongs_to_many ). This will make scoreboard.teams accessible (and return an array of Team objects).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM