Я пытаюсь связать 2 модели - Athletes
и Results
Они имеют следующие поля:
Спортсмены - :name :year :gender
Результаты - :name :event :performance
Я добавил belongs_to :athlete
к results.rb
и добавил has_many :results
к athletes.rb
Я хотел бы использовать атрибут: name, чтобы действовать в качестве первичного ключа, используемого для связи двух моделей, поскольку предполагается, что все спортсмены будут загружены изначально, а затем просто использовать входные данные результатов до конца сезона.
Я отредактировал results_controller
до следующего:
def create
#this was the initial code....
#@result = Result.new(params[:result])
# This is the new code to try set up an association
@athlete = Athlete.where('name = ?', 'Peter')
@result = @athlete.results.create(params[:result])
respond_to do |format|
if @result.save
format.html { redirect_to @result, notice: 'Result was successfully created.' }
format.json { render json: @result, status: :created, location: @result }
else
format.html { render action: "new" }
format.json { render json: @result.errors, status: :unprocessable_entity }
end
end
конец
Это, однако, приводит к ошибке undefined method 'results' for #<ActiveRecord::Relation:0x36a2b28>
. Я также надеялся использовать строку @athlete = Athlete.where("name = ?", params[:name])
, однако она продолжает давать значение параметра NULL ...
Кто-нибудь может указать мне правильное направление, пожалуйста?
Дополнительная информация:
Результаты миграции
class CreateResults < ActiveRecord::Migration def change
create_table :results do |t|
t.string :name
t.string :event
t.decimal :performance
t.timestamps
end
#add in new line here
add_index :results, :name
end end
миграция спортсменов
class CreateAthletes < ActiveRecord::Migration
def change
create_table :athletes do |t|
t.string :name
t.integer :year
t.string :gender
t.timestamps
end
end
end
Result.rb:
class Result < ActiveRecord::Base
belongs_to :athlete
end
Athlete.rb
class Athlete < ActiveRecord::Base
has_many :results
end