Rails:在元素和第二级嵌套元素之间创建关联
以下系统用于管理联系人。 每个联系人都属于一个组织,每个组织都有许多位置。联系人还与上级组织的一个位置相关。 组织模型看起来像这样,
has_many :contacts
has_many :locations
accepts_nested_attributes_for :locations, :reject_if => lambda { |a| a["name"].blank? }
我希望它接受位置的嵌套属性,因为当用户添加组织时,他还可以动态为其添加位置。
联系人模型看起来像这样
has_one :location
belongs_to :organisation
accepts_nested_attributes_for :organisation
同一个故事,当添加联系人时,我希望用户能够动态添加组织,但组织需要有一个位置,因此视图中还存在第二层嵌套为组织创建位置。 它工作正常,它添加了联系人,它添加了组织和位置,它创建了位置和组织之间的关联,但发生的情况是我在联系人中有一个字段“location_id”,我想在其中包含 id动态为组织添加的位置。有谁知道通过模型来完成此操作的干净方法,或者我是否必须通过在控制器中进行一些调整来解决它?
The following system is for managing contacts.
Each contact belongs to an organisation, and each organisation has many locations. A contact is also related to one location from the parent organisation.
The organisation model looks like this
has_many :contacts
has_many :locations
accepts_nested_attributes_for :locations, :reject_if => lambda { |a| a["name"].blank? }
I want it to accept nested attributes for locations because when a user adds an organisation he can also add a location for it on the fly.
The contact model looks like this
has_one :location
belongs_to :organisation
accepts_nested_attributes_for :organisation
Same story, when a contact is added I want the user to be able to add the organisation on the fly, but the organisation needs to have a location, so a second level of nesting exists in the view to also create the location for the organsiation.
It works fine, it adds the contact, it adds the organisation and the location, it creates the association between the location and the organisation but what happens is that I have a field "location_id" in contact and I want to have in that the id of the location added for the organisation on the fly. Does anyone know a clean way to do it through the model or do I have to workaround it with some tweaks in the controllers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用@location = @contact.build_location,它应该创建您当前缺少的ID,即使@contact的ID在构建时不存在。
If you use
@location = @contact.build_location
it should create the ID that you are currently missing, even though the id of @contact does not exist at the time of the build.