gpt4 book ai didi

ruby-on-rails - Rails 创建新记录而不是更新

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:03 25 4
gpt4 key购买 nike

更新记录时 Rails 应用出现问题。每次我这样做时,Rails 都会创建一条新记录,而不是编辑选择要更新的记录。

我注意到,无论我浏览是为了编辑还是创建,表单都会呈现一个 Create Flyer 按钮。所以我不确定问题是否出在与此相关的 Rails 内部。

我在这里附上了我认为相关的所有内容。任何其他信息让我知道。

对象本身是具有以下值的传单:

ActiveRecord::Schema.define(version: 20141016141700) do

create_table "flyers", force: true do |t|
t.string "event_name"
t.string "location"
t.string "genre"
t.string "date"
t.string "frequency"
t.string "tags"
t.datetime "created_at"
t.datetime "updated_at"
end

end

传单 Controller .rb

class FlyersController < ApplicationController

def index
@flyers = Flyer.all
end

def new
@flyer = Flyer.new
end

def create
Flyer.create flyer_params
redirect_to '/flyers'
end

def edit
find_params
end

def update
find_params
@flyer.update flyer_params
redirect_to '/flyers'
end

private

def flyer_params
params[:flyer].permit(:event_name, :location, :genre, :tags, :date, :frequency)
end

def find_params
@flyer = Flyer.find params[:id]
end

end

edit.html.erbnew.html.erb 都使用以下渲染:

<%= form_for Flyer.new do |f| %>

<%= f.label :event_name %>
<%= f.text_field :event_name %>

<%= f.label :location %>
<%= f.text_field :location %>

<%= f.label :genre%>
<%= f.text_field :genre %>

<%= f.label :tags %>
<%= f.text_field :tags %>

<%= f.label :date %>
<%= f.text_field :date %>

<%= f.label :frequency %>
<%= f.text_field :frequency %>


<%= f.submit %>

<% end %>

flyers_feature_spec.rb

require 'rails_helper'

describe 'flyer upload page' do
context 'no flyers uploaded' do
it 'should display a notification' do
visit '/flyers'
expect(page).to have_content 'No flyers added'
end
end

context 'adding a flyer' do
it 'should be listed on the index' do
visit '/flyers'
click_link 'Add New Flyer'
fill_in 'Event name', with: 'Hospitality'
fill_in 'Location', with: 'Brighton'
fill_in 'Genre', with: 'Drum and bass, obvs'
fill_in 'Tags', with: 'liquid'
fill_in 'Date', with: '12/12/14'
fill_in 'Frequency', with: 'Weekly'

click_button 'Create Flyer'
expect(current_path).to eq '/flyers'
expect(page). to have_content 'Hospitality'
end
end


context 'with existing flyers' do

before do
Flyer.create(event_name: 'Hospitality')
end

describe 'editing a flyer' do
it 'should update flyer details' do
visit '/flyers'
click_link 'Edit'
fill_in 'Event name', with: 'Hospitality v2'
click_button 'Update'

expect(page).to have_content 'Hospitality v2'
end
end

end
end

最佳答案

在 Controller 的edit方法中添加:

@flyer = Flyer.find(params[:id])

并将 View 的第一行更改为:

<%= form_for @flyer do |f| %>

附注您应该同时更改 edit.html.erb 和 new.html.erb,这样如果 new 由于验证而失败,它将保留正确填写的字段而不是清空它们。

关于ruby-on-rails - Rails 创建新记录而不是更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26411493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com