我在rails中使用腳手架創建應用程序,用戶可以在其中提交想法,然後所有想法都會列在主頁上。我目前只是試圖獲得提交和列表功能,但是_form.html.erb文件中生成的腳手架似乎並未提交任何內容或更新數據庫。也就是說,我既沒有收到「想法提交成功」的消息,也沒有收到「錯誤提交想法」的消息。它只是刷新表單頁面。Rails腳手架不更新數據庫
我想知道它是否與我的routes.rb文件有什麼問題,因爲在互聯網上花了很多時間後,我覺得我的大部分代碼都應該可以工作。
idea.rb
class Idea < ApplicationRecord
belongs_to :user
belongs_to :category
has_many :comments
validates :title, :user, :anonymous, :contents, presence: true
validates :deleted, inclusion: { in: [true, false]}
scope :alive, -> { where deleted: false }
def children
Comment.where(idea_id: id, deleted: false)
end
end
ideas_controller.rb
class IdeasController < ApplicationController
def index
@ideas = Idea.alive.paginate(page: params[:page], per_page: 20)
end
def show
@idea = Idea.find(params[:id])
@comments = @idea.children
@reply = Comment.new
end
def new
@idea = Idea.new
@categories = Category.all.map{|c| [ c.name, c.id ] }
end
def new_comment
@idea = Idea.find(params[:id])
@comment = Comment.new
end
def create
@idea = Idea.new(idea_params)
if @idea.save
redirect_to @idea, alert: "Idea submitted successfully."
else
redirect_to new_idea_path, alert: "Error submitting idea."
end
end
def idea_params
params.require(:idea).permit(:title, :contents, :anonymous, :category)
end
end
_form.html.erb:
<%= form_for @idea do |f| %>
<% if idea.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(idea.errors.count, "error") %> prohibited this idea from being saved:</h2>
<ul>
<% idea.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.check_box(:anonymous) %>
<%= f.label(:anonymous, "Hide my name") %>
</div>
<div class="field">
<%= f.label :contents %><br />
<%= f.text_area :contents %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
create_ideas.rb:
class CreateIdeas < ActiveRecord::Migration[5.0]
def change
create_table :ideas do |t|
t.string :title
t.text :contents
t.boolean "anonymous", limit: 1, default: false
t.boolean "deleted", limit: 1, default: false
t.timestamps
end
end
end
的routes.rb:
Rails.application.routes.draw do
resources :ideas
end
編輯:有本身沒有錯誤跟蹤,因爲我看不到任何東西 - 表單頁面重新加載剛。然而,這裏是從服務器日誌的輸出:
Started POST "/ideas" for ::1 at 2017-01-28 20:40:07 -0500
Processing by IdeasController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5ooCTQZKBv1f1+SlZyl/7tkJzLx95EpckoPBpB710JrikRJqt8wOdE0GT3bjBl1m6wIxKQhzfXmKRrvkV+RHeA==", "idea"=>{"title"=>"sadfsd", "anonymous"=>"1", "contents"=>"sdafasdf"}, "commit"=>"Create Idea"}
(0.3ms) begin transaction
(0.1ms) rollback transaction
Redirected to http://localhost:3000/ideas/new
Completed 302 Found in 26ms (ActiveRecord: 0.4ms)
發表您的錯誤跟蹤 –
@Edmund李 - 請編輯 –