在小組索引頁面上,我將顯示小組討論列表和表單以創建新討論。Rails:從表單發佈到M:M表
class Group < ActiveRecord::Base
has_many :discussions
end
class Discussion < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
控制器:
class DiscussionsController < ApplicationController
def index
@group = Group.find(params[:group_id])
@discussion = current_user.discussions.build({group_id: @group.id}) if logged_in?
@discussions = @group.discussions
end
def create
@discussion = current_user.discussions.build(discussion_params)
if @discussion.save
flash[:success] = "Discussion started."
redirect_to root_url
end
end
private
def discussion_params
params.require(:discussion).permit(:title, :content)
end
end
我的形式如下。
<%= form_for([@group, @discussion]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :title, placeholder: "Title" %>
</div>
<div class="field">
<%= f.text_area :content, placeholder: "Start a discussion..." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
但是,當表單提交時記錄的行沒有group_id時,這可以正常工作。我懷疑問題在於我在創建操作中構建討論對象的方式,但我不確定如何以不同方式進行操作。
Started POST "/groups/635601/discussions" for 127.0.0.1 at 2015-06-22 15:16:07 +1000
ActiveRecord::SchemaMigration Load (0.3ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by DiscussionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"tJWJQKb6NcS1EAaeeLramzQp82xf4hLrXt+UTzKQo8+i1ePoNLYr8jXYSgBLpSxNvoPOAfNxnim1Ln6fKJ0uiw==", "discussion"=>{"title"=>"Test1", "content"=>"Test2"}, "commit"=>"Post", "group_id"=>"635601"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 406]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "discussions" ("title", "content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["title", "Test1"], ["content", "Test2"], ["user_id", 406], ["created_at", "2015-06-22 05:16:07.883843"], ["updated_at", "2015-06-22 05:16:07.883843"]]
(13.9ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 81ms (ActiveRecord: 15.5ms)
我可以在params集合中看到group_id在那裏但在散列之外。
請發佈您的'參數日誌' – Pavan
發佈您的控制器的'新'方法! –
參數:{ 「UTF8」=> 「✓」, 「authenticity_token」=> 「Ci5uQOPaRlef6HcCYln/Ks6Ykraqqms8ysCLAa3sG1NiuyzTXLcM3j8CbJKexnqRT4h1hV79uyQ2Jv3FXsf9Bw ==」, 「討論」=> { 「標題」=> 「測試1」, 「內容」=> 「的Test2」} ,「commit」=>「發佈」,「group_id」=>「635601」} – Dercni