开发者

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

开发者 https://www.devze.com 2023-03-04 03:12 出处:网络
So开发者_如何学C 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)

So开发者_如何学C 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)

belongs_to :category

How do i do that?


While I agree with @Beerlington that you might be trying to be too clever, here's the answer:

  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...


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. 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? 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. ActiveRecord just wraps around all these functionality and then it looks like you're interacting with Ruby objects. So you can't temporarily change your database and then change back on the fly for reasonable price.

0

精彩评论

暂无评论...
验证码 换一张
取 消