I have little knowledge about SQL queries and I am new to ruby on Rails.
This is my question. I have a 2 tables Country and State. A country has many states.
I know that there has to be foreign key in State table that joins to the Country table.
So the query to get all the states in a country would be
Select *
From State
Where
State. country = Country. country
And Country.country = 'XYZ'
I need to be able to generate a form for creating a new state, which has a drop down list of countries. While creating a state the User can choose a country to which the state belongs to. This will help me retrieve all the states in a country. I know that I need to use has_many and belongs_to in Country and State Models respectively. But I fail to understand the modifications that are to be made in the controllers and views to be able to get the desired form.
To fetch all states belonging to a country in ruby/rails you’d simply call the association on the country model. eg:
This is how rails associations work. You don’t need to make the SQL yourself.
You may also like to look at all the other methods that rails provides for associations here: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods