Rails link_to 问题
我正在构建一个儿童家务应用程序。在 application.html.erb 中,我显示一个侧栏,列出孩子的姓名:
<div id="side">
<%= link_to "Home", home_path %><br />
<% @children.each do |child| %>
<%= link_to child.name, child_path(child.id) %><br />
<% end %>
</div>
单击孩子的姓名后,我希望显示所有杂务。单击上面的代码将“显示”孩子。
我在想这样的事情:
<%= link_to child.name, chore_path %><br />
..这不起作用,因为:
- 然后我丢失了 child_id...我需要他们来记录他们的家务,
- 我被路由到 http://localhost:3000/chores/1 (我只想要杂务索引)
如何在此示例中将 child_id 保留为变量但显示杂务索引?
干杯,克里斯
协会如下:
class Child < ActiveRecord::Base
has_many :completion, :dependent => :destroy
has_many :chores, :through => :completion
class Chore < ActiveRecord::Base
has_many :completions
has_many :kids, :through => :completions
class Completion < ActiveRecord::Base
belongs_to :child
belongs_to :chore
I am building a Kid's Chore App. In application.html.erb I show a side bar listing the children's names:
<div id="side">
<%= link_to "Home", home_path %><br />
<% @children.each do |child| %>
<%= link_to child.name, child_path(child.id) %><br />
<% end %>
</div>
Upon clicking a child's name, I want all chores to be displayed.. The code above will "show" the child when clicked.
I am thinking something like:
<%= link_to child.name, chore_path %><br />
.. this does not work because:
- I then lose the child_id... which I need for them to record their chores
- I am routed to http://localhost:3000/chores/1 (I just want the chores index)
How can I keep the child_id as a variable in this example but display the chore index?
Cheers, Chris
Associations below:
class Child < ActiveRecord::Base
has_many :completion, :dependent => :destroy
has_many :chores, :through => :completion
class Chore < ActiveRecord::Base
has_many :completions
has_many :kids, :through => :completions
class Completion < ActiveRecord::Base
belongs_to :child
belongs_to :chore
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
然后,您可以使用
params[:child_id]
获取操作中的子 ID,例如,链接将指向
/chores?child_id=1
。Then you can grab the child id in the action with
params[:child_id]
The link will be to
/chores?child_id=1
for example.我通常会为此场景创建子路线。
routes.rb
chores_controller.rb
现在您可以将链接编写为:
有关嵌套资源的更多信息
I generally create sub-routes for this scenario.
routes.rb
chores_controller.rb
Now you can write your link as:
More on nested resources
由于看起来您只是想在 Children#show 视图中渲染杂务的主列表,也许您可以尝试在您的 Children/show.html.erb 中渲染
'chores/index'
合适的位置。只需确保您在ChildrenController#show
方法中设置了一个主@chores
变量即可。不确定这是否是一个完整的解决方案,但这是我的贡献。Since it looks like you simply want to render the master list of Chores in the Children#show view, perhaps you could try a render
'chores/index'
in your children/show.html.erb in the appropriate location. Just make sure you get a master@chores
variable set up in yourChildrenController#show
method. Not sure if this is a complete solution, but there is my contribution.