~MODEL~
…/contract.rb
class Contract < ActiveRecord::Base
has_and_belongs_to_many :places
end
…/place.rb
class Place < ActiveRecord::Base
has_and_belongs_to_many :contracts
end
…/schema.rb
create_table “contracts”, :force => true do |t|
. . .
t.string “place”
. . .
end
create_table “contracts_places”, :id => false, :force => true do |t|
t.integer “contract_id”
t.integer “place_id”
end
create_table “places”, :force => true do |t|
t.string “name”
t.datetime “created_at”
t.datetime “updated_at”
end
~CONTROLLER~
…/contracts_controller.rb
def show # (edit)
@contract = Contract.find(params[:id])
@places = @contract.places
end
~VIEW~
…/_contract.html.erb
<%= @places.names %> # Does’t work
~CONSOLE VERSION~
Rails db:
sqlite> select * from contracts_places;
1|1
1|2
1|3
7|1
7|2
Rails console version:
ruby-1.9.2-p290 :001 > contract = Contract.first
=> #<Contract id: 1, place: “1”>
ruby-1.9.2-p290 :002 > place = contract.places
=> [#<Place id: 1, name: “Street1”, created_at: “…”, updated_at:
“…”>,
#<Place id: 2, name: “Street2”, created_at: “…”, updated_at:
“…”>,
#<Place id: 3, name: “Street3”, created_at: “…”, updated_at:
“…”>]
ruby-1.9.2-p290 :003 > place.names
NoMethodError: undefined method `names’ for #<Class:
0x00000002025150>
ruby-1.9.2-p290 :004 >
~Question~
How to output all list of places?