我有一个嵌套属性 message.rb
class Message < ActiveRecord::Base
belongs_to :trip
attr_accessible :name, :email, :subject, :body
end
属于trip.rb
class Trip < ActiveRecord::Base
has_many :messages
accepts_nested_attributes_for :messages, :allow_destroy => true
attr_accessible :messages_attributes
end
消息控制器.rb
class MessagesController < ApplicationController
def create
@trip = Trip.find(params[:trip_id])
@message = @trip.messages.create(params[:message])
redirect_to trip_path(@trip)
end
end
消息形式在 \trips\show.html.erb
<%= form_for([@trip, @trip.messages.build]) do |f| %>
<div class="field">
<%= f.label :name%><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :subject %><br />
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
它也应该出现在那里 \trips\show.html.erb
<h2>Messages</h2>
<% @trip.messages.each do |message| %>
<p>
<b>NAme:</b>
<%= message.name %>
</p>
<b>Email:</b>
<%= message.email %>
</p>
<b>Subject:</b>
<%= message.subject %>
</p>
<b>Message:</b>
<%= message.body %>
</p>
<% end %>
问题是它只是没有。
我的 Development.log。
, "id"=>"44"} [1m[35mTrip Load (0.0ms)[0m SELECT "trips".* FROM "trips" WHERE "trips"."id" = ? LIMIT 1 [["id", "44"]] [1m[36mCategory Load (0.0ms)[0m [1mSELECT "categories".* FROM "categories" INNER JOIN "categories_trips" ON "categories"."id" = " categories_trips"."category_id" WHERE "categories_trips"."trip_id" = 44[0m [1m[35mLocation Load (0.0ms)[0m SELECT "locations".* FROM "locations" WHERE> "locations"."id" = 18限制 1 [1m[36mCACHE (0.0ms)[0m [1mSELECT "trips".* FROM "trips" WHERE "trips"."id" = ? 限制 1[0m [1m[35m图像加载(1.0ms)[0m 选择“图像”。
我真的不明白为什么,我确实设置了 attr_accessible。你能帮我吗 ?谢谢你!
更新
通过rails控制台它可以工作:
irb(main):019:0> first_trip.messages.create(name: "emils2") ←[1m←[35mSQL (2.0ms)←[0m INSERT INTO "messages" ("body", "created_at", "email ", "name", "subject", "trip_id", "updated_at") 值 (?, ?, ?, ?, ?, ?, ?) [["body", nil], ["created_at", Wed, 2012 年 8 月 1 日 13:52:29 UTC +00:00], ["email", nil ], ["name", "emils2"], ["subject", nil], ["trip_id", 32], [ “updated_at”,2012 年 8 月 1 日星期三 13:52:29 UTC +00:00]]
32,created_at:“2012-08-01 13:52:29”,updated_at:“2012-08-01 13:52:29”>
我的 routes.rb 也嵌套了:
resources :trips do
resources :messages
end