Ruby/Rails。将变量传递给参数
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
Posts.where(category: true)
中的category
将不是变量,它将是一个硬编码符号:category
,所以它不会工作。相反,写这个:
def posts_for_all_pages(category)
@posts = Posts.where(category => true)
end
一个小小的改动,却有着不一样的意义。
然后当你调用这个方法时,你传递一个符号给它:
posts_for_all_pages(:photos)
我的应用程序中有很多页面。对于每个页面,我都需要创建一个新变量并描述方法。如果我需要更改某些内容,我将不得不在每一页上进行更改。所以想法是在 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
Posts.where(category: true)
中的category
将不是变量,它将是一个硬编码符号:category
,所以它不会工作。相反,写这个:
def posts_for_all_pages(category)
@posts = Posts.where(category => true)
end
一个小小的改动,却有着不一样的意义。
然后当你调用这个方法时,你传递一个符号给它:
posts_for_all_pages(:photos)