【发布时间】:2017-03-20 20:35:36
【问题描述】:
我有一个 Rails 应用程序,如下所示: 一个位置模型,它存储一些地理信息(基本上是一个位置)、一个帖子模型和一个用户模型。后模型可以有一个位置。用户模型可以将一个位置作为家庭位置,将另一个位置作为远程位置:
class Location < ApplicationRecord
belongs_to :locationable, polymorphic: true
end
class Post < ApplicationRecord
has_one :location, as: :locationable
accepts_nested_attributes_for :location
end
class User < ApplicationRecord
has_one :homelocation, as: :locationable, class_name: 'Location'
has_one :remotelocation, as: :locationable, class_name: 'Location'
accepts_nested_attributes_for :homelocation, :remotelocation
end
帖子和位置的东西效果很好。如果我从用户模型中删除“has_one”行并将 homelocation 重命名为 location,一切都很好。但是,如果我希望用户拥有两个不同的位置,则在尝试保存更改时会收到“未经许可的参数:homelocation,remotelocation”错误。
我的 users_controller 有一个
def user_params
params.require(:user).permit(:admin, :name, :motto, homelocation_attributes: [:id, :address], remotelocation_attributes: [:id, :address])
end
就像 posts_controller 有一个
def post_params
params.require(:post).permit(:title, :content, location_attributes: [:id, :address])
end
我的表单如下所示:
.form-group.string.required.user_homelocation_address
label.control-label.string.required for="user_homelocation_address"
abbr title="required"
| Home Location
input#user_homelocation_address.form-control.string.required name="user[homelocation][address]" type="text"
.form-group.string.required.user_remotelocation_address
label.control-label.string.required for="user_remotelocation_address"
abbr title="required"
| Remote Location
input#user_remotelocation_address.form-control.string.required name="user[remotelocation][address]" type="text"
那么为什么这适用于一个“has_one”,而不适用于两个?
【问题讨论】:
-
对所有这些东西的很好的解释都在这里,顺便说一句:stackoverflow.com/questions/23814903/…@sirramongabriel - 只是遗憾的是,他似乎也无法弄清楚我的问题;阅读最后一段。
标签: ruby-on-rails activerecord polymorphism polymorphic-associations has-one