![](/img/trans.png)
[英]I'm running into the error “param is missing or the value is empty: user_id” when trying to display user profile pages
[英]param is missing or the value is empty: {:user_id=>9}
我已經看過類似的問題,但我不知道如何解決。 我做了幾次失敗的嘗試。 訪問http://localhost:3000/users/9/propuneres/new
時,出現此錯誤“ PropuneresController#new參數中的ActionController :: ParameterMissing丟失或值為空:{:user_id => 9}”。
routes.rb
Rails.application.routes.draw do
get 'users/show'
devise_for :users
get 'static/home'
get 'static/despre'
resources :users, only: [:show] do
resources :propuneres
end
root to: 'static#home'
普魯尼瑞
class Propunere < ActiveRecord::Base
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :propuneres
end
propuneres / new.html.erb
<h2> Propunere Nouă </h2>
<%= form_for @propunere, url: user_propuneres_path(@propunere), html: { method: :get } do |f| %>
<ul>
<% @propunere.errors.full_messages.each do |error| %>
<li><%= error %></li>
<% end %>
</ul>
<p>
<%= f.label :titlu %><br />
<%= f.text_field :titlu %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
propuneres_controller.rb
before_action :prop
def new
@propunere = Propunere.new()
end
def create
@propunere = Propunere.new
@propunere.titlu = params[:propunere][:titlu]
@propunere.body = params[:propunere][:body]
@propunere.user_id = params[:propunere][:user_id]
@propunere.save
redirect_to propunere_path(@propunere)
end
def index
end
private
def prop
params.require(user_id: current_user.id).permit(:titlu, :body,)
end
end
我認為至少有兩件事情我做錯了。 感謝您的耐心等待。
在表單上,必須將用戶分配給url(如果要用作嵌套資源)
user_propuneres_path(@user, @propunere)
在控制器上(您將此問題標記為Rails 3,我假設您沒有使用gem'strong_parameters'),然后可以刪除方法prop
並將此代碼用於new並創建:
def new
@user = User.find(params[:user_id])
@propunere = @user.propuneres.build
end
def create
@user = User.find(params[:user_id])
@propunere = @user.propuneres.new(params[:propunere])
if @propunere.save
redirect_to user_propunere_path(@user, @propunere)
else
render 'new'
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.