Rails 用于自引用 HABTM Active Record 对象的嵌套编辑表单
好吧,这个真是太棒了。我有一个 ActiveRecord 对象,其中包括如下关系:
class Sample < ActiveRecord::Base
has_and_belongs_to_many :related_samples,
:class_name => "Sample",
:join_table => "related_samples",
:foreign_key => "sample_id"
:associated_foreign_key => "related_id"
end
这是它的方案:
def self.up
create_table :samples do |t|
t.string :related_info
t.string :name
#There's other info, but it is not related to this problem
end
create_table :related_samples, :id => false do |t|
t.references :sample
t.references :related
t.timestamps
end
end
这非常有效。当我请求 Sample_object.lated_samples 时,它会提供我分配给它的任何其他 Sample 对象。
问题来自于我的视图的编辑操作。我的目标是允许用户通过从所有可用示例的列表中选择现有的相关示例对象来将其替换为其他对象。我想在 fields_for 辅助方法内部实现这一点(如果可能),这样更新就非常简单。我不知道如何实现这个,或者我什至可以。是否可以?如果是这样,怎么办?
OK, this one is a doozy. I have an ActiveRecord object that, among other things, includes a relationships as follows:
class Sample < ActiveRecord::Base
has_and_belongs_to_many :related_samples,
:class_name => "Sample",
:join_table => "related_samples",
:foreign_key => "sample_id"
:associated_foreign_key => "related_id"
end
And here's the scheme for it:
def self.up
create_table :samples do |t|
t.string :related_info
t.string :name
#There's other info, but it is not related to this problem
end
create_table :related_samples, :id => false do |t|
t.references :sample
t.references :related
t.timestamps
end
end
This works perfectly. When I ask for sample_object.related_samples, it gives me whatever other Sample objects I assigned it.
The problem comes with the edit action for my views. My goal is to allow a user to replace an existing related Sample object to a different one by selecting it from a list of all available Samples. And I want to implement this (if possible) inside of a fields_for helper method, so that doing the update is really simple. I'm not sure how to implement this, or I even can. Is it possible? And if so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚意识到一些非常重要的事情可能使这个问题无法解决。当我说我希望能够更改与另一个相关的 Sample 对象时,我指的是对其的引用。示例:
我想做一些事情,以便我可以使用 Sample4 代替另一个 Sample,这样它就变成:
但我希望 Sample3 保持不变。这意味着引用需要更改,我认为没有任何方法比修改我的数据库方案更容易。所以,如果你还有想法,我很想听听,但我可能会改变一些事情。谢谢,SO社区!
I just realized something extremely important that likely makes this question impossible to solve. When I say I want to be able to change a Sample object another one is related to, I mean the reference to it. Example:
I want to do something so that I can use Sample4 in place of another Sample, so that it becomes:
But I want Sample3 to remain intact. This means the references need to change, which I see no way of doing in any way that would be easier than modifying my database scheme. So, if you still have an idea, I'd love to hear it, but I'll likely be changing things. Thanks, SO community!