Here is the problem that I have been trying to solve, but I haven’t found a way that doesn’t feel like an outright hack. I have 2 objects, Warehouse and StateCity. The Warehouse object has a foreign key to a StateCity object ( state_city_id ).
Now when a user creates a Warehouse, I would like them to be able to input the State and City. Currently they can do so, and I just check the submitted params for the State and City and then create or find the corresponding ActiveRecord object. Now when they go to view the Warehouse in my view I’ve oscillated between using a helper to extract the State/City from the StateCity object if it exists and adding a method on my model to perform the same function like below
def show_state( warehouse )
if warehouse.state_city.nil? == false
return warehouse.state_city.state
end
return ""
end
def show_city( warehouse )
if warehouse.state_city.nil? == false
return warehouse.state_city.city
end
return ""
end
Unfortunately, neither the helper method or fattening up the model with extra functions seems very natural as I have to use one for the creation of the object and another for the vieiwng of the object.
I was wondering if anyone has any advice on a better way to solve the Warehouse-StateCity problem. Any help is greatly appreciated.
First off you could write and if statement of this kind like so:
but I’m sure that’s not the answer you are looking for.
I’m assuming that you always want a Warehouse to be associated with a StateCity. If that is the case then your user always needs to select the state and city whenever a warehouse is created and that logic is handled by your controller and validated by your Warehouse model.
If all your validations are correct then all you need to do in your show action of your Warehouse model is fetch the StateCity object from your warehouse:
And then in your view just access the fields
@state_city.stateand@state_city.city. I’m not entirely sure how you are creating these StateCity objects but that sounds pretty much how you want to do things.If your state_city is nil you could handle it different ways depending on what you want displayed or not. If you still want to display the warehouse show view then in the view you could do a check like
If you want to tell the user to update the state city for example you’d handle that from the controller by doing
what that will do is it’ll check if your state_city is null then it’ll redirect the user to whatever action you want.