0

Experienced Java developer, new to Rails - wondering about belongs_to relationship in scaffolding.

Saw another answer like this

Does rails scaffold command support generate belongs_to or many to many model middle table migration info?

and followed the rails generate scaffold_controller obj:references pattern.

The index/show page is showing #<MyClass:xxxx> instead of the string I want - is there a method in the target class (parent side of the belongs_to) I need to override to specify the identifier?

Also in the edit view, it looks like it's trying to modify the reference as a string rather than as drop-down - is there something I need to specify to make that happen?

Thanks!

BTW - I was able to get similar scaffolding to work in Django and Grails, where the foreign key turned into a drop-down; I'm hoping Rails is equally easy and I'm just missing it.

Community
  • 1
  • 1
wrschneider
  • 17,913
  • 16
  • 96
  • 176

1 Answers1

1

You can override the #to_s method on the instances, as it is the one being called.

class FooDoodle < ActiveRecord::Base
  def to_s
    name
  end
end

That's when showing a record.

However, when you're actually using the form to set the associations, scaffold will only generate an input field in the view so you can enter the id. You could have a dropdown menu for example, but the options for that dropdown would somehow have to be selected in a manner.

For example, if there are 2000 possible associated records, which ones do you show? Do you show the 2000? Only the first 10? That logic would go into your controller.

So, for example:

class FooDoodlesController < ApplicationController
  def edit
    @foodoodle = FooDoodle.find(params[:id])

    @friends = @foodoodle.possible_friends # or else
  end
end

and using select and options_for_select as choices

# _form.html.erb

<%= form_for @foodoodle do |f| %>
  <%= f.label :friend %>
  <%= f.select :friend, @friends.map{ |p| [p.to_s, p.id] } %>
Jonathan Allard
  • 18,429
  • 11
  • 54
  • 75