has_many / belongs_to:显示每个关联的记录

时间:2013-08-28 15:35:23

标签: ruby-on-rails

我有两个模型及其相关表以belongs_to和has_many关系链接在一起。

这是架构

ActiveRecord::Schema.define(version: 20130827203308) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "posts", force: true do |t|
    t.text    "message"
    t.integer "student_id"
  end

  add_index "posts", ["student_id"], name: "index_posts_on_student_id", using: :btree

  create_table "students", force: true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.string   "number"
    t.string   "college"
    t.string   "password"
    t.float    "budget"
    t.string   "picture"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

我可以去rails console并执行

a = Student.find(1)
c = a.posts.create(:message => "testing")
c.save!

(0.4ms)  BEGIN
   (0.4ms)  COMMIT
 => true 

我不知道如何在视图中将其绘制回来。我不知道如何在rails控制台中将其绘制回来。

我的index.html.erb视图中有

Message: <%= @student.posts.message %>

并在我的控制器中使用@student = Student.find(1)

并获得

undefined method `message'

在我的localhost:3000

它不是一种方法。我想从我的桌子上画一些东西。

1 个答案:

答案 0 :(得分:3)

@student.posts返回属于此特定Student对象的Post对象列表。

您需要遍历学生的每个帖子以显示其消息:

student = Student.first # retrieves the first Student of the DB
posts = student.posts # retrieves the student's posts
posts.each do |post| # loop through each post of the student
  puts post.message # outputs the content of the message attribute of the post
end

在视图中,它会有点相同:

Student: 
<%= @student.first_name + ' ' + @student.last_name %>

Posts: 
<% @student.posts.each do |post| %>
  Post #<%= post.id %>
  Message: <%= post.message %>
<% end %>