在 Rails 中,显示嵌套资源不起作用



我正在使用嵌套资源。当我单击已创建的目标时,我不断收到此错误:

param is missing or the value is empty: goal

它将我引导到"参数要求..."线:

    private
        def goal_params
            params.require(:goal).permit(:text)
        end

我不确定是什么原因造成的。我可以创建和显示列表。但是当我点击一个目标时,我会收到此错误。我是 rails 的新手,我已经到了尽头。

我的观点:

<h1>Listing goals</h1>
<table>
  <tr>
    <th>Text</th>
    <th></th>
  </tr>
  <% @user.goals.each do |goal| %>
    <tr>
      <td><%= link_to goal.text, user_goals_path(@user, @goal)%></td>
    </tr>
  <% end %>
</table>

<h2>Add a comment:</h2>
<%= form_for([@user, @user.goals.build]) do |form| %>
  <p>
    <%= form.text_area :text %>
  </p>
  <p>
    <%= form.submit %>
  </p>
<% end %>

我的控制器:

class GoalsController < ApplicationController
    def index
        @user = User.find(params[:user_id])
        @goal = @user.goals.find(goal_params)
    end
    def show
        @user = User.find(params[:user_id])
        @goal = @user.goals.find(:id) 
        #also tried goal_params and :goal_id instead of :id
    end
    def new
        @user = User.find(params[:user_id])
        @goal = @user.goals.new
    end

    def create 
        @user = User.find(params[:user_id])
        @goal = @user.goals.build(goal_params)
        @goal.user = current_user
        if @goal.save
            redirect_to new_user_goal_path, notice: "Success!~"
        else 
            redirect_to new_user_goal_path, alert: "Failure!"
        end
        #to root_path
    end 
    private
        def goal_params
            params.require(:goal).permit(:text)
        end
end

我的路线:

Rails.application.routes.draw do
  devise_for :users
  resources :user do
    resources :goals
  end
  devise_scope :user do
    authenticated :user do
      root 'home#index', as: :authenticated_root
    end

    unauthenticated do
      root 'devise/sessions#new', as: :unauthenticated_root
    end
  end
end

我的节目.html.erb:

<p>
  <strong>Text:</strong>
  <%= @goal.text %>
</p>

第一件事,在节目中

@goal = @user.goals.find(:id) 

应该是

@goal = @user.goals.find(params[:id]) 

你说你在show行动中尝试过@user.goals.find(goal_params),我也在你的index行动中看到了这一点。这将调用 goal_params 方法,该方法需要params[:goal]而您的indexshow请求不会发送到服务器,只有当您提交表单时,您才会拥有该参数。这是导致错误的原因。

第二件事,您的index应该使用

@goals = @user.goals

而不是

@goal = @user.goals.find(goal_params)

此外,strong parameters仅用于createupdate操作,以避免大量分配到我们的数据库。它不用于find记录。

最新更新