Ruby on Rails显示嵌入式模型
问题描述:
嘿,这可能是一个非常简单的问题,但我似乎无法让我的show.html.erb页面显示,我是一个真正的初学者。这是在轨道上的红宝石。这里是我的代码:Ruby on Rails显示嵌入式模型
Post.rb
class Post < ActiveRecord::Base
attr_accessible :artist
has_many :songs
end
Song.rb
class Song < ActiveRecord::Base
attr_accessible :lyric, :name, :song_id
belongs_to :post
end
CreatePost迁移
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :artist
t.string :song
t.timestamps
end
end
end
CreateSong迁移
class CreateSongs < ActiveRecord::Migration
def change
create_table :songs do |t|
t.text :lyric
t.string :name
t.integer :song_id
t.timestamps
end
end
end
show.html.erb
<center><h1><%= @post %></h1></center>
<p> Songs: </p>
<% @post.song.song_id.each do |s| %>
<p>
<%= s.name %>
</p>
<% end %>
<% form_for [@post, Song.new] do |f| %>
<p>
<%= f.label :name, "Artist" %><br />
<%= f.text_field :name %><br />
<%= f.label :body, "Song Name:" %><br />
<%= f.text_field :body %>
</p>
<p>
<%= f.submit "Add Song" %>
</p>
<% end %>
答
它看起来像你缺少的控制器。
Ruby on Rails中的控制器在模型和视图之间调节数据。
我建议你可能要在应用中创建一个控制器/控制器文件夹,如:
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
end
end
你还需要确保岗位资源是建立在routes文件。
在config/routes.rb中的文件,你可以把
resources :posts
这告诉/帖网址是指岗位控制器轨。
对于所有不同的移动部件,RoR入门可能有点棘手。我强烈建议使用railscasts.com作为简短教程片段。另请参阅peepcode.com了解更多深入的说明。