问题描述
这是我的模型:
class Drama < ApplicationRecord
has_many :reviews
has_many :users,:through => :reviews
validates :name,uniqueness: true
accepts_nested_attributes_for :reviews
accepts_nested_attributes_for :users
结束
class Review < ApplicationRecord
belongs_to :user
belongs_to :drama
结束
class User :reviews 验证:用户名,唯一性:真,存在:真 验证:电子邮件,唯一性:真,存在:真 has_secure_password 结束
这是不保存/创建的嵌套表单!
<div>
<%= form_for @drama do |f| %>
<h2>Drama Info</h2>
<strong>Name: <%= f.text_field :name %></strong><br>
<strong>Genre: <%= f.text_field :genre %></strong><br>
<h2>Review Info</h2>
<%= f.fields_for :reviews,@drama.reviews.build do |r| %>
<%= r.label :title %>
<%= r.text_field :title %><br>
<%= r.label :rating %>
<%= r.number_field :rating %><br>
<%= r.label :content %>
<%= r.text_area :content %><br>
<%end%>
<%= f.submit %>
<%end%>
</div>
这是我的路线:
Rails.application.routes.draw do
resources :dramas do
resources :reviews,only: [:new,:show]
end
resources :dramas
resources :users
resources :reviews
get '/auth/facebook/callback',to: 'sessions#create_with_fb'
get '/',to: 'sessions#home'
get '/signup',to: 'users#new'
post '/signup',to: 'users#create'
get '/login',to: 'sessions#new'
post '/login',to: 'sessions#create'
post '/logout',to: 'sessions#destroy'
# For details on the DSL available within this file,see https://guides.rubyonrails.org/routing.html
end
这是我的戏剧控制器:
class DramasController < ApplicationController
before_action :find_by_drama,only: [:edit,:update,:destroy,:show]
before_action :current_user,only: [:create,:edit,:destroy]
def index
@dramas = Drama.all
end
def new
@drama = Drama.new
@drama.reviews.build
end
def show
session[:drama_id] = @drama.id
# @drama = Drama.find(session[:drama_id])
end
def create
@drama = Drama.new(drama_params)
if @drama.save
redirect_to dramas_path
else
render :new
end
结束
def update
@drama = Drama.update(drama_params)
redirect_to dramas_path
end
def edit
end
def destroy
@drama.destroy
redirect_to dramas_path
end
private
def drama_params
params.require(:drama).permit(
:name,:genre,reviews_attributes: [
:title,:rating,:content
]
)
end
结束
我的数据库。架构:
ActiveRecord::Schema.define(version: 2020_12_19_073757) do
create_table "dramas",force: :cascade do |t|
t.string "name"
t.string "genre"
t.datetime "created_at",precision: 6,null: false
t.datetime "updated_at",null: false
end
create_table "reviews",force: :cascade do |t|
t.integer "user_id"
t.integer "drama_id"
t.string "title"
t.text "content"
t.integer "rating"
t.datetime "created_at",null: false
end
create_table "users",force: :cascade do |t|
t.string "username"
t.string "email"
t.string "password_digest"
t.datetime "created_at",null: false
end
end
请帮忙!被卡住了
解决方法
不需要 @drama.reviews.build
中的 fields_for
部分,因为您已经在 new
操作中构建了评论。尝试删除它,看看它是否有效。然后在 edit
操作中添加 @drama.reviews.build
,如果您还想在该操作中构建另一个评论。在视图中构建嵌套属性可能会导致一些奇怪的行为。如果它仍然不起作用,请从正在运行的应用程序中发布跟踪信息,或者在视图中尝试 @drama.errors.inspect
或使用 puts
在服务器日志中打印错误。