我不了解新并在轨道中创建关联



我想要达到的效果

我已经在电影和时间表之间创建了一个关联,但是我不知道如何实例化这个关联,即使在阅读了Rails指南之后。

<标题>

代码

db/模式

# movies
create_table "movies", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name"
t.integer "year"
t.string "description"
t.string "image_url"
t.integer "is_showing"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
#schedules
create_table "schedules", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "movie_id", null: false
t.time "start_time", null: false
t.time "end_time", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["movie_id"], name: "index_schedules_on_movie_id"
end

模型movie.rb

class Movie < ApplicationRecord
has_many :schedules
end

schedule.rb

class Schedule < ApplicationRecord
belongs_to :movie
end

控制器

时间表

class SchedulesController < ApplicationController
def index
@movies = Movie.joins(:schedules).select("movies.*", "schedules.*")
end
###############################################################################
# I don't get it.
def new
@schedule = @movie.build_schedules()
end

def create
@schedule = Schedule.new(schedule_params) 
@schedule.save
redirect_to schedules_path
end
###############################################################################

private
def schedule_params
params.require(:schedule).permit(:start_time, :end_time)
end  
end

new.html.erb


<!DOCTYPE html>
<html lang="en">
<head>
<%= render 'shared/head' %>
<title>schedule/new</title>
</head>
<body>
<%= form_with model: @schedule, url: movie_schedules_path do |form| %>
<div class="field">
<%= form.label :start_time %>
<%= form.date_field :start_time %>
</div>
<div class="field">
<%= form.label :end_time %>  
<%= form.date_field :end_time %>
<%= form.submit %>
</div>
<% end %>
</body>
</html>

我已经尽力了。

·查看Rails指南。我使用build代替new,但是用了一个论点。我不知道这里的参数部分需要什么。
# Rails Guide
@book.author = @author
@author = @book.build_author(author_number: 123,
author_name: "John Doe")

您想做@movie.schedules.build来实例化@movie.schedules关联的新记录,因为它是一个has_many。

您也可以执行@movie.schedules.create(schedule_params)一步创建与Movie实例关联的Schedule。

record.build_xxx仅适用于has_many/belongs_to关联(例如,您可以执行some_schedule.build_movie)。

最新更新