更新:已解決。謝謝BusyMark!
編輯:這是根據BushyMark下面的答案修改的。我想我正確地提出了所有建議的更改,但當用戶提交消息時,我仍然無法將post_type_id保存到數據庫。Collection_select問題
我的應用程序有一個配置文件頁面。在個人資料頁面上,頁面的所有者可以輸入更新並點擊「提交」。更新消息在沒有頁面重新加載的情況下出現(即Ajax)。
它基本上看起來像你的Twitter主頁。但是,我們的用戶在輸入更新時還會選擇一個「類型」信息。消息類型是預先填充的列表。我已經將它作爲模型並將其作爲種子數據加載到應用程序中。
因此:有一個配置文件模型,後期模型和post_type模型。
profile has_many :posts
post belongs_to :post_type
post_type has_many :posts
樁模型也有這樣的:attr_accessible :message, :post_type_id
routes.rb中看起來是這樣的:
map.resources:用戶,:has_one => :profile, :has_many => :posts
map.resources:post_types
帖子控制器有這種創建帖子的方法:
def create
@post = current_user.profile.posts.build(:message => params[:message], :post_type_id => params[:post_type_id])
if @post.save
redirect_to user_profile_path
else
flash[:notice] = "Message failed to save."
redirect_to user_profile_path
end
end
「顯示」查看配置文件頁面,這一切都發生這個樣子的:
<% form_tag(:controller => "posts", :action => "create") do %>
<%= label_tag(:message, "Update your people") %><br />
<%= text_area_tag(:message, nil, :size => "27x3") %>
<div class="updateSubmit"><%= submit_tag("Update") %></div>
<%= label_tag(:type_id, "Optional: Update type", :class => 'typeLabel') %>
<%= collection_select(:post, :post_type_id, PostType.all, :id, :name, {:prompt => true}) %>
<% end %>
<% @profile.profile.posts.each do |c| %>
<%=h c.message %></div>
<p><%=h c.post_type %></p>
<p>Posted <%=h time_ago_in_words(c.created_at) %> ago</p>
<% end %>
這是背景。這是問題。用我目前的設置,當用戶提交他的消息時,消息被髮送到帖子數據庫表,但是post_id沒有。
我選擇標籤渲染這樣的:
<select id="post_post_type_id" name="post[post_type_id]"><option value="">Please select</option>
這是輸出我在日誌中得到,當我提出一個帖子:
處理PostsController#創建(對於IP在2009-09-03 03 :03:08)[POST]
Parameters: {"message"=>"This is another test.", "commit"=>"Update", "action"=>"create", "authenticity_token"=>"redacted", "post"=>{"post_type_id"=>"3"}, "controller"=>"posts", "user_id"=>"1"}
User Load (0.3ms) SELECT * FROM "users" WHERE ("users"."id" = 1)
Profile Load (0.7ms) SELECT * FROM "profiles" WHERE ("profiles".user_id = 1) LIMIT 1
Post Create (0.5ms) INSERT INTO "posts" ("message", "updated_at", "post_type_id", "profile_id", "created_at") VALUES('Hello', '2009-09-03 20:40:24', NULL, 1, '2009-09-03 20:40:24')
這裏是我的架構中的有關部分,每BushyMark的評論更新:
`create_table "post_types", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end`
`create_table "posts", :force => true do |t|
t.text "message"
t.integer "profile_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "post_type_id"
end`
我做了所有這些更改,但仍然無法在用戶提交時將post_type_id保存到數據庫中。我將用新的設置修改我的問題。 – MikeH 2009-09-03 20:50:12
好吧,明白了。有用!。謝謝。 – MikeH 2009-09-03 22:39:26