简体   繁体   English

有什么方法可以为铁路注入即时的联系吗?

[英]is there any way to inject an association on the fly for rails?

So for instance I have a Guest model, 例如,我有一个来宾模型

While i'm using the Guest model on some action, id like to inject this association (only on that action) 当我在某些动作上使用Guest模型时,id喜欢注入该关联(仅在该动作上)

belongs_to :category 相关类:类别

How do i do that? 我怎么做?

It sounds like you may be trying to get a little clever with your code. 听起来您可能正在尝试使代码变得更聪明。 While it may be possible to do, it's not a native feature and would likely introduce a lot of hacky metaprogramming, and therefore some potentially nasty bugs. 尽管有可能做到这一点,但这不是本机功能,并且可能会引入很多hacky元编程,因此会带来一些潜在的令人讨厌的错误。 I would recommend taking a step back and seeing if you can rethink the problem you're trying to solve. 我建议您退后一步,看看您是否可以重新考虑要解决的问题。 Are you using RESTful controllers? 您正在使用RESTful控制器吗? It's hard to say based on your question, but usually the answer is no when you start asking questions like this. 根据您的问题很难说,但是通常当您开始问这样的问题时答案是否定的。 Does your controller have too much logic? 您的控制器逻辑是否过多? Maybe some of what you're trying to do can be moved to models. 也许您想要做的一些事情可以转移到模型中。 If you provide more information about what you're doing, you'll probably get more useful responses. 如果您提供有关正在执行的操作的更多信息,则可能会得到更有用的答复。

Theoretically maybe it's possible but in your case it can't be accomplish. 从理论上讲也许有可能,但就您而言,这是不可能完成的。 Because belongs_to is a database issue, it means one of the database table has id to another table. 由于belongs_to是数据库问题,因此意味着一个数据库表具有另一个表的ID。 ActiveRecord just wraps around all these functionality and then it looks like you're interacting with Ruby objects. ActiveRecord只是包装了所有这些功能,然后看起来您正在与Ruby对象进行交互。 So you can't temporarily change your database and then change back on the fly for reasonable price. 因此,您不能临时更改数据库,然后以合理的价格即时更改数据库。

While I agree with @Beerlington that you might be trying to be too clever, here's the answer: 尽管我同意@Beerlington的观点,即您可能会尝试变得过于机灵,但这是答案:

  1. Make a module like so: 像这样制作一个模块:

     module Categorical def self.included(included_class) included_class.instance_eval do # from here to the end of this block, imagine that you are in the class # source itself. Add associations or instance methods, for example belongs_to :category end end end 
  2. Now, include that module in your class: 现在,在您的班级中包含该模块:

     class Guest < ActiveRecord::Base include Categorical .... end 

And there you have it! 在那里,您拥有了!

This could be useful if you are also adding named_scopes to your Categorical class, or other helper methods... 如果您还向您的Categorical类或其他帮助器方法中添加了named_scopes,这可能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM