我看过像这样的问题,但我无法弄清楚如何解决它。我做了几次不成功的尝试。我在PropuneresController #new中得到了这个错误" ActionController :: ParameterMissing
param丢失或值为空:{:user_id => 9}"访问http://localhost:3000/users/9/propuneres/new
时。
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'
propunere.rb
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
我认为至少有两件事我做错了。 感谢您的耐心等待。
答案 0 :(得分:2)
在表单中,您必须将用户分配给url(如果您要用作嵌套资源)
user_propuneres_path(@user, @propunere)
在控制器上(您将此问题标记为Rails 3,我假设您没有使用gem&#39; strong_parameters&#39;),然后您可以删除方法prop
并将此代码用于新并创建:
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