[英]Ruby/Rails. Passing variable into parameters
我的应用中有很多页面。 对于每个页面,我需要创建一个新变量和描述方法。 如果我需要改变一些东西,我将不得不改变每一页。 因此,我们的想法是在application_controller.rb
创建通用方法。
例如,我的帖子中有很多类别,并且针对我所做的页面定位了一些类别: @posts_for_interesting = Post.where(interesting: true)
,其他类别,例如: @posts_for_photos = Post.where(photos: true)
。
而application_controller.rb
必须看起来像这样:
def posts_for_all_pages(category)
@posts = Posts.where(category: true)
end
例如, photos_controller.rb
必须如下所示:
posts_for_all_pages(photos)
我如何将这些photos
传递给Post.where(category: true)
?
就在您的原始代码中:
def posts_for_all_pages(category)
@posts = Posts.where(category: true)
end
该category
中Posts.where(category: true)
将不是一个变量,这将是一个硬编码的符号:category
,所以它不会工作。 相反,写下这个:
def posts_for_all_pages(category)
@posts = Posts.where(category => true)
end
一个小小的变化,但绝对有不同的含义。
然后,当您调用该方法时,您将符号传递给它:
posts_for_all_pages(:photos)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.