我有一个简单的控制器,它是通过脚手架创建的,并具有“显示”功能。
在通过脚手架创建的视图中,我有一个仅在特定条件下出现的图像。
我想在控制器中设置或评估条件并将其发送到视图。我不确定如何做到这一点,或者这是否是正确的方法。
我有一个简单的控制器,它是通过脚手架创建的,并具有“显示”功能。
在通过脚手架创建的视图中,我有一个仅在特定条件下出现的图像。
我想在控制器中设置或评估条件并将其发送到视图。我不确定如何做到这一点,或者这是否是正确的方法。
条件一般应在视图文件中使用 erb 或 haml 处理。如果您使用条件更新您的问题,那么我会看到更新我的答案以反映它。现在,我将使用一个常见的条件。
假设您只想在某个对象出现时显示图像。让我们想象一下,您的对象中有一个特色字段充当标志 (1,0)。
如果这个对象是一篇文章,我们可以检查视图文件中的条件。控制器将从模型中获取文章:
-# articles_controller show action
@article = Article.find(params[:id])
..
-# views/articles/show.html.erb
<% if @article.featured? %>
// show image here
<% end %>
请记住,这是一个不一定正确的示例条件。这只是为了说明我最初的方法。
我不建议您根据这种情况使用 javascript 来隐藏/显示,因为您随后将逻辑放入 javascript 中,而它可以从您的视图文件中轻松管理。
如果条件很复杂,您可以将其移动到模型中,并执行以下操作:
if @article.some_complex_condition?
..而不是在你的控制器文件中有那个复杂的条件。这允许您在远离特定控制器的情况下重用条件并使其更具可测试性。
If you just want to show and hide an image based on a certain condition, than you can do that with JQuery. You shouldn't put anything in the controller that is view-centric.
You can also get the id of whatever data element is in 'show' and pass it to the JavaScript.
JQuery has show()
and hide()
methods that would work for you. Here's the documentation on the hide method: http://api.jquery.com/hide/
Basically, if you had a certain id for your image, you'd do something like this:
$(document).ready(function() {
$("#myImage").hide();
if (some_condition === true) {
$("#myImage").show();
}
});
You can put that code in your application.js
file.
I whipped up a simple JsFiddle demonstrating a way to show and hide with buttons: http://jsfiddle.net/phillipkregg/92RDS/
Of course, the code may be different depending on what you are trying to do.
If you need to get the 'id' of the object in the 'show' view, than you can put a script tag at the bottom of your show view like this:
<script type="text/javascript">
var my_show_object = <%= @some_object.id %> //this will be the specific id of whatever the object is that you passed from the controller
alert(my_show_object); //this helps with debugging to see if you have the right id
</script>
If you need more than the id, and you want to get the entire Rails object and represent it as Javascript - just do this at the bottom of your rails 'show' view:
<script type="text/javascript">
var my_object = <%= @your_rails_object.to_json %>;
console.log(my_object); //This code allows you to look in the console and see exactly what your object looks like.
</script>
Just like the last one, @your_rails_object
is the variable that you have in your show view in the controller. This will return it as a json object so that you can get the id or whatever properties it has.
Also, if you are just learning Rails, I would recommend this online book: http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
That's how I learned Rails - the book is excellent and free.