开发者

Rails option_groups_from_collection_for_select in a weird way

开发者 https://www.devze.com 2023-01-09 07:20 出处:网络
Ok so I have a optimization that I need to make to a Rails site but the relationsips are not conventional. So my problem is I need a option_groups_from_collection_for_select to go from the state and t

Ok so I have a optimization that I need to make to a Rails site but the relationsips are not conventional. So my problem is I need a option_groups_from_collection_for_select to go from the state and the cities are below. This can normally be achieved if the State has_many cities and the City belongs_to a state. The problem is the relationships are no there and the State is hardcoded in the table. For example:

select * from states;
+----+----------------------+------+
| id | name                 | abbr |
+----+----------------------+------+
|  2 | Alabama              | AL   |
|  3 | Alaska               | AK   |
|  4 | Arizona              | AZ   |
|  5 | Arkansas             | AR   |


select * from cities;
+-------------------------+-------+----------------------+
| name                    | state | permalink            |
+-------------------------+-------+----------------------+
| Orlando                 | FL    | orlando-fl           |
| West Palm Beach         | FL    | west-palm-beach-fl   |
| Tampa                   | FL    | tampa-fl             |
| Ft. Lauderdale          | FL    | ft-lauderdale-fl     |
| Jacksonville            | FL    | jacksonville-fl      |
| Atlanta                 | GA    | atlanta-ga           |

So the option_groups_from_collection_for_select is expecting a State.all and City.all with relationships but I don't know what I ne开发者_如何学JAVAed to get all the data to make the

option_groups_from_collection_for_select(@state, :cities, :name, :id, :name, 3)


Just set up the relationship between state and city with custom keys. Like so:

Under state:

has_many :cities, :primary_key => :abbr, :foreign_key => :state

under city:

belongs_to :state,  :primary_key => :abbr, :foreign_key => :state
0

精彩评论

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