我正在尝试动态显示与另一列中所选项目关联的一列项目。见底部的图片。所以明确地说,如果你点击程序“减肥”,将会显示减肥计划中的周期。
Tt就像用Program.find(3).cycles.each
中的3替换单击任何程序的id一样简单,但几个小时后,我无法弄清楚如何动态替换代码块中的代码。真正感谢任何正确方向的帮助!
这是屏幕截图中页面的html:
<h2>Program</h2>
<ul class="sortable" data-update-url="<%= sort_programs_url %>">
<% @programs.each do |program| %>
<%= content_tag_for :li, program, class: "card" do %>
<%= link_to program.name, program %>
<% end %>
<% end %>
</ul>
<%= link_to 'Add New Program', new_program_path, :class => 'add-new' %>
<!-- Column one end -->
</div>
<div id="col2">
<!-- Column two start -->
<h2>Cycle</h2>
<ul class="sortable">
<% Program.find(3).cycles.each do |cycle| %>
<li class="card" id="cycle-<%= cycle.id %>">
<%= truncate(cycle.name, :length => 20, :separator => ' ') %>
</li>
<% end %>
</ul>
<%= link_to 'Add New Cycle', new_cycle_path, :class => 'add-new' %>
<!-- Column two end -->
</div>
模特:
class Program < ActiveRecord::Base
has_many :cycles_programs
has_many :cycles, :through => :cycles_programs
class Cycle < ActiveRecord::Base
has_many :cycles_programs
has_many :programs, :through => :cycles_programs
答案 0 :(得分:0)
我认为你应该将界面逻辑移到JavaScript中。这是一个例子:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div { width: 300px; float: left; margin-right: 20px; }
li { list-style: none; border: 1px solid #555; border-radius: 5px; padding: 20px; margin: 5px;}
</style>
</head>
<body>
<div class="program">
<h2>Program</h2>
<ul id="programs">
</ul>
<a href="#add_program">Add Program</a>
</div>
<div class="cycle">
<h2>Cycle</h2>
<ul id="cycles">
</ul>
<a href="#add_cycle">Add Cycle</a>
</div>
<script type="text/javascript">
// Source data via ajax? constructed as part of building page?
var data = [
{name:'Fat Loss', cycles: ['Cycle 1', 'Cycle 2']},
{name:'Licks balls', cycles: ['Cycle 3', 'Cycle 4']},
{name:'klasdjfa', cycles: ['ReCycle', 'Deep Cycle', 'UniCycle']},
{name:'Testing Programs', cycles: ['Scotch', 'Soda']},
{name:'Hypertrophy', cycles: ['Clockwise', 'CounterClockwise', 'Sidewise']}
];
// display set of cycles
var display_cycles = function(cycle_list) {
var cycles = document.getElementById('cycles');
var cycle;
cycles.innerHTML = '';
for ( var k in cycle_list ) {
cycle = document.createElement('li');
cycle.innerHTML = cycle_list[k];
cycles.appendChild(cycle);
}
};
var programs = document.getElementById('programs');
var program, trigger;
// initial programs display
for ( var j in data ) {
program = document.createElement('li');
trigger = document.createElement('a');
trigger.setAttribute('href', '#'+j);
trigger.setAttribute('class', 'trigger_cycles');
trigger.setAttribute('onclick', 'display_cycles(data['+j+']["cycles"])');
trigger.innerHTML = data[j]['name'];
program.appendChild(trigger);
programs.appendChild(program);
}
// Cycles for the first program
display_cycles(data[0]['cycles']);
</script>
</body>
</html>
答案 1 :(得分:0)
我相信在Rails中执行此操作的正确方法是移动我想要显示和消失的部分代码,并使用JS使这些部分显示和消失。我可以找到关于如何做这类事情的最好的教程是nested forms上的Ryan Bates rails教程。
在RailsCast中,一旦您进入有关如何显示和删除表单字段的部分,您将很好地了解如何执行此操作。