【发布时间】:2014-07-14 21:03:57
【问题描述】:
我是 Ruby on rails 的初学者。应用程序有 4 个模型。州、省、区和市。
型号
app/models/state.rb
Class State < ActiveRecord::Base
has_many :provinces
end
app/models/province.rb
Class Province < ActiveRecord::Base
belongs_to :state
has_many :districts
end
app/models/district.rb
Class District < ActiveRecord::Base
belongs_to :province
has_many :cities
end
app/models/city.rb
Class City < ActiveRecord::Base
belongs_to :district
end
Schema.rb
ActiveRecord::Schema.define(version: 20140714165543) do
create_table "states", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "provinces", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "state_id"
end
add_index "provinces", ["state_id"], name: "index_provinces_on_state_id"
create_table "districts", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "province_id"
end
add_index "districts", ["province_id"], name: "index_districts_on_province_id"
create_table "citys", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "district_id"
end
add_index "citys", ["district_id"], name: "index_citys_on_district_id"
end
我正在使用 simple_form gem。我为所有模型创建 CRUD。我的问题是
当我创建一些状态时。然后我在浏览器中创建省份并分配给状态 error 。 state_id 为零
class ProvincesController < ApplicationController
#GET /Provinces/new
def new
@province = Province.new
end
# GET /provinces/1/edit
def edit
end
# POST /provinces
# POST /provinces.json
def create
@province = Province.new(province_params)
respond_to do |format|
if @province.save
format.html { redirect_to @province, notice: 'Province was successfully created.' }
format.json { render :show, status: :created, location: @province }
else
format.html { render :new }
format.json { render json: @province.errors, status: :unprocessable_entity }
end
end
end
end
省内_form.html.erb
<%= simple_form_for(@province) do |f| %>
<% if @province.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@province.errors.count, "error") %> prohibited this province from being saved:</h2>
<ul>
<% @province.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<%= f.association :state %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
【问题讨论】:
-
一方面,似乎没有任何方法称为provincial_params。
-
def province_paramsparams.require(:province).permit(:name)end -
你能告诉我们你在
submitform时生成的server log吗? -
-
尝试将您的
province_params更改为params.require(:province).permit(:name,:state_id)
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2