Hi all, I am creating a multiple-storefront shopping cart in Rails, and have run into a small problem. In addition to the cart, line-item, product, and order models (pretty much standard for this sort of thing), I have a Storefront model which locates the current storefront (by examining the domain name), and initializes itself. This works fine throughout, and by declaring a "current_storefront" method in application.rb and application_helper.rb, I have the current store's info available throughout all controllers and views. OK so far. However, I'd like to make some changes to the other models on the fly depending on which storefront is loaded. For example, products have a cross-sell relationship to themselves that varies by storefront. For another example, order validations change from storefront to storefront (i.e., "State" is not a required field in my UK store, but it is in my US store). The question I have, then, is how to load an instance of Storefront and have that instance available in the other model definitions (order, product, etc). It seems like there's probably an elegant Ruby idiom for this I am missing. I'd interested to see how others solve this problem, as it seems to be a pattern repeating in a few of my sites. much thanks! - michael.
on 2006-04-05 19:33
on 2006-04-05 21:31
I'm pretty new at this so I'll be interested to see what the more experienced people say but here's my two sense. I'm assuming your model can't just reference the Storefront instance set in your application controller because models don't talk to controllers (controllers talk to models). So one method is to have your controller explicitly pass your models a reference to the Storefront. @cart.storefront = @storefront But if you do this a lot then some type of a builder pattern might be cleaner. Have your Storefront instantiate the models, give each model a reference to itself, and return the model. @cart = @storefront.new_shopping_cart inside Storefront def new_shopping_cart cart = New Shopping_cart() cart.storefront = self cart end Note I am new at this so I quite easily could have made mistakes in the actual code but hoepfull you get the idea. - William