I'm opening this easy to fix issue for people looking for easy things to fix :).
Steps to reproduce
rails new myapp
rails g scaffold currency name
rails g scaffold account name currency:belongs_to
And try to tie an account with a currency. The account view should be pointing to currency_id.
@spastrino How can i know the currency_id while creating account? If there was select box of currencies, i can select one and that can have value which will be currency_id from database. But here, as it is textbox, i don't know what is the id of the currency.
select box is fine too
I wrote a test for this, but need feedback. Looks like Rails::Generators::NamedBase is where I want to look? Pointers?
run_generator ["account", "name", "currency:belongs_to"]
assert_file "app/models/account.rb", /belongs_to :currency/
assert_migration "db/migrate/create_accounts.rb" do |m|
assert_method :change, m do |up|
assert_match(/t\.string :name/, up)
assert_match(/t\.belongs_to :currency/, up)
assert_file "app/controllers/accounts_controller.rb" do |content|
assert_instance_method :account_params, content do |m|
assert_match(/permit\(:name, :currency_id\)/, m)
assert_file "app/views/accounts/_form.html.erb" do |content|
assert_match(/<%= f\.text_field :name %>/, content)
assert_match(/<%= f\.text_field :currency_id %>/, content)
$ ruby -Itest test/generators/scaffold_generator_test.rb
Run options: --seed 61346
Finished in 1.572028s, 8.9057 runs/s, 152.6690 assertions/s.
Expected /<%= f\.text_field :currency_id %>/ to match "<%= form_for(@account) do |f| %>\n <% if @account.errors.any? %>\n <div id=\"error_explanation\">\n <h2><%= pluralize(@account.errors.count, \"error\") %> prohibited this account from being saved:</h2>\n\n <ul>\n <% @account.errors.full_messages.each do |msg| %>\n <li><%= msg %></li>\n <% end %>\n </ul>\n </div>\n <% end %>\n\n <div class=\"field\">\n <%= f.label :name %><br>\n <%= f.text_field :name %>\n </div>\n <div class=\"field\">\n <%= f.label :currency %><br>\n <%= f.text_field :currency %>\n </div>\n <div class=\"actions\">\n <%= f.submit %>\n </div>\n<% end %>\n".
14 runs, 240 assertions, 1 failures, 0 errors, 0 skips
You should be looking at https://github.com/rails/rails/blob/master/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
You have to look at attributes https://github.com/rails/rails/blob/master/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb#L25
@spastorino same thing applies to :references right? ie: should be :currency_id
right. They are aliases
@rafaelfranca Thank you, I have a patch, submitting a PR now
Use GeneratedAttribute#column_name if #reference? scaffold_generator …
…in _form view [Fixes #11573]
Level: Easy tag is an excellent idea. please tag more issues like this.
Thanks a lot @zzak may Rails be with you ;)