Ruby/Rails:动态更改共享部分中的属性
这应该是某人的布局...
我正在尝试根据哪个控制器/模型调用包含表单字段的部分来更改表单字段的属性...
问题(如下)与 parent_id... 引用狗表中的两列之一。它需要是
kennel_id
或 master_id
,具体取决于该部分渲染在哪个视图中。
使用 Ruby/Rails 语言/语法/工具动态地进行渲染还不够舒服更改此设置,而不会陷入 if/else 语句中。
我正在调用共享部分并传入局部变量:
= render "dogs/form", :parent => @kennel
或者
= render "dogs/form", :parent => @master
在部分中我想:
= form_for ([parent, target.dogs.build]) do |f|
= render "shared/error_messages", :target => parent
.field
= f.label :name
= f.text_field :name
.field
= f.hidden_field :parent_id ### <= PROBLEM
.actions
= f.submit 'Save'
This should be a layup for someone...
I'm trying to change a form field's attribute depending on which controller/model is calling the partial containing the form fields...
The issue (below) is with parent_id
... which references one of two columns in a dogs table. It needs to either be kennel_id
or master_id
depending on which view this partial is being rendered in.
Not comfortable enough, yet, with Ruby/Rails language/syntax/tools to dynamically change this without getting bogged down in if/else
statements.
I'm calling a shared partial and passing in a local variable:
= render "dogs/form", :parent => @kennel
or
= render "dogs/form", :parent => @master
In the partial I'd like to:
= form_for ([parent, target.dogs.build]) do |f|
= render "shared/error_messages", :target => parent
.field
= f.label :name
= f.text_field :name
.field
= f.hidden_field :parent_id ### <= PROBLEM
.actions
= f.submit 'Save'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是大声思考:
我不知道
parent
模型是否有正确的名称,但你可以这样做:但这看起来不对。那么,为什么不将其作为参数传递呢?
或者,在狗模型上创建别名来处理某种动态委托:
但这也很糟糕。这种关系可以是多态的吗?然后你就可以省略切换。
只是一些想法。希望其中之一对您有意义......
Just thinking out loud:
I don't know if the
parent
-models have the proper names for it, but you could do something like:But that doesn't look right. So, why not pass it as an argument?
Or, create aliases on the dog model to handle some sort of dynamic delegation:
But that sucks too. Could the relation be polymorphic? Then you can leave out the switching.
Just some ideas. Hopefully one of them makes sense to you...
哇,我最初的答案还不够接近。我认为您需要的是多态关联: http://guides.rubyonrails.org /association_basics.html#polymorphic-associations 这样,父类可以是您需要的任何类。
Wow, my initial answer wasn't even close. I think what you'll want is a polymorphic association: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations This way, the parent can be whatever class you need it to be.