0

だから私は2つのモデルを持っていますTopicClient。クライアントhas_and_belongs_to_many :topics、およびトピックhas_and_belongs_to_many :clients

基本的に、私がしたいのは...誰かが私のところに行くときTopic#index、彼らがそこにたどり着いた方法(つまり、経由client/:id/topicsまたは単に/topics)に応じて、createとnewの動作を変えたいです。つまり、/topicsでは、トピックを作成するだけです。でclient/:id/topicsトピックを作成し、そのクライアントに割り当てます。

私のルートは次のようになります。

  resources :topics
  resources :clients do
    resources :topics
  end

私のトピックコントローラーは次のようになります。

  def new
        if params[:client_id]
            @client = Client.find(params[:client_id])
            @topic = @client.topics.build
        else
            @topic = Topic.new
        end

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @topic }
    end
  end

  def create
        if params[:client_id]
            @client = Client.find(params[:client_id])
            @topic = @client.topics.build(params[:topic])
        else
        @topic = Topic.new(params[:topic])
        end

    respond_to do |format|
      if @topic.save
        format.html { redirect_to @topic, notice: 'Topic was successfully created.' }
        format.json { render json: @topic, status: :created, location: @topic }
      else
        format.html { render action: "new" }
        format.json { render json: @topic.errors, status: :unprocessable_entity }
      end
    end
  end

views/topics/_form.html.erbはこのように見えます:

<%= form_for([@client, @topic]) do |f| %>
...
<% end %>

ただし、これからアクションを実行するとclient/:id/topics、ログは次のようになります。

Started GET "/clients/1/topics/new" for 127.0.0.1 at 2012-09-10 14:33:06 -0500
Processing by TopicsController#new as HTML
  Parameters: {"client_id"=>"1"}
  Client Load (0.2ms)  SELECT "clients".* FROM "clients" WHERE "clients"."id" = ? LIMIT 1  [["id", "1"]]
  Rendered topics/_form.html.erb (3.6ms)
  Rendered topics/new.html.erb within layouts/application (4.7ms)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
   (0.2ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = 1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))
  Rendered layouts/_navigation.html.erb (7.2ms)
  Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 61ms (Views: 57.0ms | ActiveRecord: 0.7ms)

それはよさそうだ...ここではすべてが順調に進んでいるようだ。しかし、それはPOST物事が機能していないように見えるということです:

Started POST "/clients/1/topics" for 127.0.0.1 at 2012-09-10 14:33:13 -0500
Processing by TopicsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"J172LuZQPv8=", "topic"=>{"name"=>"AMZN"}, "commit"=>"Create Topic", "client_id"=>"1"}
  Client Load (0.2ms)  SELECT "clients".* FROM "clients" WHERE "clients"."id" = ? LIMIT 1  [["id", "1"]]
   (0.1ms)  begin transaction
  SQL (186.2ms)  INSERT INTO "topics" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", Mon, 10 Sep 2012 19:33:13 UTC +00:00], ["name", "AMZN"], ["updated_at", Mon, 10 Sep 2012 19:33:13 UTC +00:00]]
   (4.6ms)  commit transaction
Redirected to http://localhost:3000/topics/4
Completed 302 Found in 198ms (ActiveRecord: 191.1ms)

クライアントへの新しいトピックの割り当てがないことに気付くでしょう。

私は何が欠けていますか?

ありがとう!

編集1

作成アクションにputsデバッグステートメントを追加しました。これは、POSTアクションの実行後に取得した結果です。これは、次のparams[:client_id]ものだけでなく、を取得していることを示していparams[:id]ます。

Served asset /application.js - 304 Not Modified (1ms)
**************************************************
This is the params[:client_id] => {3}
**************************************************
This is the params[:id] => {}


Started POST "/clients/3/topics" for 127.0.0.1 at 2012-09-10 15:06:31 -0500
Processing by TopicsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"J172LuZQc5NYoiMSzDD3oY9vGmxxCX0OdxcGm4GSPv8=", "topic"=>{"name"=>"TEST2"}, "commit"=>"Create Topic", "client_id"=>"3"}
  Client Load (0.2ms)  SELECT "clients".* FROM "clients" WHERE "clients"."id" = ? LIMIT 1  [["id", "3"]]
   (0.1ms)  begin transaction
  SQL (0.7ms)  INSERT INTO "topics" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", Mon, 10 Sep 2012 20:06:31 UTC +00:00], ["name", "TEST2"], ["updated_at", Mon, 10 Sep 2012 20:06:31 UTC +00:00]]
   (3.3ms)  commit transaction
Redirected to http://localhost:3000/topics/6
Completed 302 Found in 11ms (ActiveRecord: 4.3ms)

編集2:

それで、私はうまくいくように見える何か他のものを試しました、しかし私は上記がうまくいかない理由を知りたいです。

私の場合、Topic#createこれを行うだけです:

@client = Client.find(params[:client_id])
@topic = Topic.new(params[:topic])
@client.topics << @topic

正常に動作します。

.buildしかし、繰り返しになりますが...なぜHABTMが使用できないのか、またはこのような状況にあるのかを知りたいと思います。

4

2 に答える 2

1

params[:client_id]問題はあるかもしれないと思いますparams[:id]

puts作成アクションのifelseブロックにステートメントを入れて、ページにアクセスしたときにどのステートメントが表示されているかを確認できますか(トピックの作成)

編集

ネストされたオブジェクト属性の動的な構築をサポートするには、モデルにaccepts_nested_attributes_forを含める必要があります。

これを参照してください。

于 2012-09-10T19:58:32.130 に答える
0

@clientオブジェクトのビルドが完了した後、明示的にsaveを呼び出す必要があるようです。

そうしないと、ActiveRecordはトランザクションを保存せず、join_tableに新しいレコードを挿入しません。

于 2012-09-10T20:22:19.300 に答える