1

我有一个 World 父对象和一个 State 子对象。我正在尝试创建一个新的 State 对象,但 rails 没有找到世界 ID。我正在尝试从世界显示页面链接到新的状态表单,并且 url 显示.../worlds/1/states/new了为什么这没有在父 ID 上出现?错误应该来自控制器中的这条线@world = World.find(params[:id])。我(params[:world_id])什至尝试过使用。

为简洁起见,我只在此处发布相关代码。

世界.rb

class World < ApplicationRecord
  belongs_to :user
  has_many :states
end

状态.rb

class State < ApplicationRecord
  belongs_to :world
  belongs_to :user
end

states_controller.rb

class StatesController < ApplicationController
  before_action :set_state, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @states = State.all
  end

  def new
    @world = World.find(params[:id])
    @state = @world.states.build
  end

  def create
    @world = World.find(params[:id])
    @state = @world.states.build(state_params)
    @state.user = current_user

    respond_to do |format|
      if @state.save
        format.html { redirect_to @state, notice: 'State was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private
    def set_state
      @state = State.find(params[:id])
    end

    def state_params
      params.require(:state).permit(:name, :summary, :history, :population, :inception, :life_expectancy, :land_mass,
                                    :climate, :industry, :education, :mythology, :law, :culture, :world_id, :user_id)
    end
end 

worlds/show.html.erb 中新状态表单的链接:

<%= link_to 'New State', new_world_state_path(@world) %>

路线.rb

Rails.application.routes.draw do
  resources :states
  resources :worlds
  devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' }
  root to: "home#index"

  resources :users
  resources :worlds do
    resources :states
  end
end

状态/_form.html.erb

<div class="form">
  <%= form_for(state) do |f| %>
    <% if state.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(world.errors.count, "error") %> prohibited this state from being saved:</h2>

        <ul>
        <% state.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
        </ul>
      </div>
    <% end %>

    <%= f.text_field :name, placeholder: 'Name' %><br />

    <fieldset>
      <legend>Basic Info</legend>
        <%= f.text_area :summary, placeholder: 'Summary About', rows: 6 %><br />
        <%= f.text_area :history, placeholder: 'History', rows: 6 %><br />
        <%= f.text_area :climate, placeholder: 'Climate', rows: 3 %><br />
        <%= f.text_area :industry, placeholder: 'Industry', rows: 3 %><br />
        <%= f.text_area :education, placeholder: 'Education', rows: 3 %><br />
        <%= f.text_area :culture, placeholder: 'Culture', rows: 3 %><br />
        <%= f.text_area :law, placeholder: 'Legal System, Crime & Punishment', rows: 3 %><br />
        <%= f.text_area :mythology, placeholder: 'Mythology', rows: 3 %><br />
    </fieldset>

    <fieldset>
      <legend>Quick Stats</legend>
        <%= f.text_field :inception, placeholder: 'Inception' %><br />
        <%= f.text_field :population, placeholder: 'Population' %><br />
        <%= f.text_field :life_expectancy, placeholder: 'Ave. Life Expectance' %><br />
        <%= f.text_field :land_mass, placeholder: 'Land Mass' %><br />
    </fieldset>

    <p><%= f.submit %></p>
  <% end %>
</div>

单击“新状态”链接时的rails控制台结果

Started GET "/worlds/1/states/new" for 70.196.17.76 at 2017-05-22 13:43:47 +0000
Cannot render console from 70.196.17.76! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StatesController#new as HTML
  Parameters: {"world_id"=>"1"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 2], ["LIMIT", 1]]
  World Load (0.1ms)  SELECT  "worlds".* FROM "worlds" WHERE "worlds"."id" = ? LIMIT ?  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.4ms)



ActiveRecord::RecordNotFound (Couldn't find World with 'id'=):

app/controllers/states_controller.rb:13:in `new'
  Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
  Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
  Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (4.7ms)
  Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
  Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.6ms)
  Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
  Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
  Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (36.6ms)
4

2 回答 2

2

修改你的link_to助手以指定并告诉 Rails 你通过它发送的参数是什么:

从:

<%= link_to 'New State', new_world_state_path(@world) %>

至:

<%= link_to 'New State', new_world_state_path(id: @world) %>

id因为您正试图World通过:id作为参数来查找。

还尝试更改param在您设置@world变量的控制器中收到的内容:

def new
  @world = World.find(params[:world_id])
  ...
end

show.html.erb

<%= link_to 'New World', new_world_state_path(world_id: @world) %>

更新:我们做了什么:

app/views/worlds/show.html.erb更改参数的设置方式中:

从:

<%= link_to 'New Nation', new_world_state_path(world_id: @world_id) %> # @world_id wasn't defined

至:

<%= link_to 'New Nation', new_world_state_path(world_id: @world.id) %>

/app/views/states/_form.html.erb添加world_idhidden_field

<%= f.hidden_field :world_id, value: @world.id %>

然后app/controllers/states_controller.rb改变接收参数的方式:

def new
  @world = World.find(params[:world_id])
  @state = @world.states.build
end

def create
  @world = World.find(params[:state][:world_id])
  ...
于 2017-05-22T13:34:40.197 回答
2

传递给 :new 操作的 world_id 可能不会在表单上传递回 create 操作。

您的 state_params 期望 :world_id 被发回,因此添加一个隐藏字段以将其发送回表单。

新的.html.erb

<%= f.hidden_field :world_id, :value => @world.id %>

并将创建操作更新为

@world = World.find(params[:world_id])
于 2017-05-22T13:44:36.797 回答