【发布时间】:2014-03-21 05:39:53
【问题描述】:
我是 Ruby on Rails 的新手,并试图通过一个简单的应用程序来学习它。我要做的是使用嵌套属性将详细信息保存到数据库中的不同表中。我在终端中收到未经许可的参数:位置错误。
这是我的文件..
状态.rb
class State < ActiveRecord::Base
has_many :locations
end
城市.rb
class City < ActiveRecord::Base
has_many :locations
end
位置.rb
class Location < ActiveRecord::Base
belongs_to :user
belongs_to :state
belongs_to :city
end
用户.rb
class User < ActiveRecord::Base
has_many :locations
accepts_nested_attributes_for :locations
end
用户控制器.rb
class UserController < ApplicationController
def new
end
def create
p "======================="
p params
p "======================="
p user_params
p "-----------------------"
@user = User.new(user_params)
@user.save
redirect_to @user
end
def update_city_select
@cities = City.where(state_id: params[:state_id]).order(:name) unless params[:state_id].blank?
respond_to do |format|
format.html { render layout: false }
format.js
end
end
def show
# @user = User.find(params[:id])
# @location = Location.find(params[:id])
end
private
def user_params
params.require(:user).permit(:id,:firstname, :lastname,
:locations_attributes=>[:id,:user_id,:state_id,:city_id]
)
end
end
new.html.erb
<html>
<head></head>
<body>
<%= form_for :user, url: users_path do |j| %>
<div id="first_name">
<label>First Name</label>
<div>
<%= j.text_field :firstname %>
</div>
</div>
<div id="last_name">
<label>Last Name</label>
<div>
<%= j.text_field :lastname %>
</div>
</div>
<%= j.fields_for :locations do |jl| %>
<%= render 'location_fields', :j => jl %>
<% end %>
<div>
<div id="submit">
<%= j.submit %>
</div>
</div>
<%end%>
<script type="text/javascript">
$("#state_name").change(function() {
var state = $('#state_name :selected').val();
$.ajax({
url: '/student_profile/update_city_select',
type: 'GET',
data: {
state_id: state
},
success: function(response) {
$('#city_name').html(response);
}
});
});
</script>
</body>
</html>
和_location_fields.html.erb
<div id="state_name">
<label>Location[State]</label>
<div>
<%= j.select :state_id, State.all.map{|j| [j[:name], j[:id]]} %>
</div>
</div>
<div>
<label>City</label>
<div id="city_name">
<%= j.select :city_id, {} ,{} %>
</div>
</div>
我的页面中有这 4 个字段。名字和姓氏被保存到用户表中。我想要实现的是我想将 state_id 和 city_id 保存到位置表。 State 和 City 表有一组变量。州和城市是下拉列表。选择一个州后,相应的城市将被加载到城市下拉列表中。
这是终端的输出..
"======================="
{"utf8"=>"✓", "authenticity_token"=>"7zmznmSLQ+D/089mZLjrT0H784lsX1ERilyvP68jG4I=", "user"=>{"firstname"=>"Nidhin", "lastname"=>"Besole", "locations"=>{"state_id"=>"3"}}, "city_id"=>"28516", "commit"=>"Save User", "controller"=>"user", "action"=>"create"}
"======================="
Unpermitted parameters: locations
{"firstname"=>"Nidhin", "lastname"=>"Besole"}
"-----------------------"
Unpermitted parameters: locations
提前致谢。
【问题讨论】:
标签: mysql ruby-on-rails ruby ruby-on-rails-3