我正在制作簡單的 CRUD,目前的目標是添加資料。但是,我發現無法添加任何資料,并且終端日志還顯示“[Webpacker] Everything's up-to-date.Nothing to do”,表示沒有錯誤資訊。
根據我在控制器中的設計,新資料肯定失敗了,所以我停在了new.html.erb。我猜這與模型的關系有關。
這是模型用戶
class User < ApplicationRecord
has_many :reviews
has_many :recipes, through: :reviews
end
這是模型食譜
class Recipe < ApplicationRecord
has_many :reviews
belongs_to :user
end
這是模型評論
class Review < ApplicationRecord
belongs_to :user
belongs_to :recipe
end
這是食譜控制器
class RecipesController < ApplicationController
def index
@recipes = Recipe.all
end
def new
@recipe = Recipe.new
end
def create
@recipe = Recipe.new(recipe_params)
if @recipe.save
redirect_to recipes_path, notice: "Successful!"
else
render :new
end
end
private
def recipe_params
params.require(:recipe).permit(:title, :money)
end
end
這是網頁
<h1>Add New One</h1>
<%= form_for(@recipe) do |r| %>
<%= r.label :title, "Title" %>
<%= r.text_field :title%>
<%= r.label :money, "Budget" %>
<%= r.text_field :money %>
<%= r.submit %>
<% end %>
<%= link_to "Back to list", recipes_path %>
uj5u.com熱心網友回復:
您應該首先添加一個回呼以確保只有登錄用戶才能創建食譜(除非您真的想讓匿名用戶創建/更新/洗掉食譜)。
例如,使用 Devise,您將使用它的authenticate_user!助手,如果用戶未通過身份驗證,它將保釋并重定向到登錄路徑:
class RecipesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
# ...
end
如果您正在重新發明身份驗證輪,您應該創建一個用于阻止訪問的類似方法。
然后,您將初始化當前用戶的資源:
class RecipesController < ApplicationController
before_action :authenticate_user!, except: [:show, :index]
def create
@recipe = current_user.recipes.new(recipe_params)
if @recipe.save
redirect_to recipes_path, notice: "Successful!"
else
render :new
end
end
end
在這里,我假設您有一個current_user方法可以根據存盤會話的 id 檢索用戶。
由于您有一個間接關聯,這將在表中創建一行,reviews其中用戶 id 和配方 id 作為 recipies 表中的記錄。
您還希望在表單中顯示驗證錯誤,以便用戶獲得反饋。
uj5u.com熱心網友回復:
您可能是對的,這是與 belongs_to 關系相關的驗證錯誤。您應該顯示表單的驗證錯誤,如此處所述https://guides.rubyonrails.org/getting_started.html#validations-and-displaying-error-messages
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460249.html
標籤:轨道上的红宝石
