[英]Generate method dynamically using strong params in Rails
Is it possible to generate a dynamic method using the strong parameter I get from my view? 是否可以使用从视图中获得的强参数生成动态方法?
In my view I will generate a different path according to the card the user clicks on. 在我看来,我将根据用户单击的卡生成不同的路径。 Then, in the controller I want to generate a dynamic method using the parameter obtained from the view, but I'm not sure how to write that.
然后,在控制器中,我想使用从视图获取的参数生成动态方法,但是我不确定如何编写该方法。 Thanks!
谢谢!
show.html.erb
<div class="branch-names">
<% @branches.each do |branch| %>
<div>
<%= image_tag "cat.jpeg" %>
<%= link_to "#{branch.name} Posts", send("#{branch.branch}_posts_path") %>
</div>
<% end %>
</div>
posts_controller.rb
def self.define_category(name)
define_method(name) do |params[:id]|
@posts = Post.where(category_id = params[:id])
end
end
define_category("#{params[:id]}")
You shouldn't define method based on user input. 您不应基于用户输入定义方法。 It may cause security issue, and for sure it causes performance penalty related to method cache invalidation .
这可能会导致安全问题,并且肯定会导致与方法缓存无效相关的性能 下降 。
Instead you can create one method that have an alternarive on params[:id]
and then decide what to show to the user: 相反,您可以创建一个对
params[:id]
产生异议的方法,然后决定向用户显示什么:
class MyController
def branches
case params[:id]
when('cat')
do_cat_stuff
when('dog')
do_dog_stuff
end
end
end
For having routes like /posts/cats
you do not have to add dynamic methods. 对于具有
/posts/cats
类的路由,您不必添加动态方法。 Think of branch
like of an id of category: 可以将
branch
想象为类别的ID:
routes: 路线:
resources :post_categories, only:[:index, :show]
view: 视图:
...
<%= link_to "#{branch.name} Posts", post_category_path(branch.branch) %>
PostCategories controller: PostCategories控制器:
def show
@posts = Post.where(category_id: params[:id])
end
Also you can make posts
a nested resource under categories and use a more RESTful structure with /post_categories/some_branch/posts
mapping to posts#index
您还可以使
posts
成为类别下的嵌套资源,并使用更具RESTful结构的/post_categories/some_branch/posts
映射到posts#index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.