0

그래서 두 모델 Topic, Client이 있습니다. A 클라이언트 has_and_belongs_to_many :topics 및 주제 has_and_belongs_to_many :clients. 누군가가, 내가의 동작이 다르게 새로운 &를 작성하려면 그들이 거기에 도착하는 방법에 (즉, 하나를 통해 client/:id/topics하거나 /topics)를 따라 내 Topic#index에 갈 때중첩 된 리소스와 중첩되지 않은 리소스 모두에서 만들기 작업을 수행하려면 어떻게해야합니까?

기본적으로, 내가 일이 원하는 것은 ...입니다 . 즉 /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) 

당신은 알 클라이언트에 새로운 주제를 더 할당이 없습니다.

무엇이 누락 되었습니까?

감사합니다.

편집 한

추가 내 생성 작용에 디버그 문을두고,이 내가 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 또는이 상황에서 사용되지 않는 이유를 알고 싶습니다.

답변

1

나는 문제가 params[:client_id]에있는 것 같아 params[:id] 일 수 있습니다.

당신은 당신이 필요로하는

편집 작업을 만들 당신의 경우 다른 블록에 puts 문을 넣어, 당신은 (주제를 만들 수) 페이지를 명중 할 때 다음 게재되는 하나 볼 수 모델에 accepts_nested_attributes_for을 포함시켜 동적으로 중첩 된 객체 속성을 지원할 수 있습니다.

this을 참조하십시오.

+0

그건 문제가되지 않습니다. 그 결과를 포함하도록 질문을 업데이트했습니다. – marcamillion

+0

또한, 내 로그 출력에서 ​​질문에 포함 된 올바른 params [: client_id]를 찾고 params 해시에 올바르게 포함하고 있음을 알 수 있습니다. 그것으로 올바른 일을하지 않는 것뿐입니다. – marcamillion

+0

흠 ... 편집 2 후 꽤 이상하게 보입니다. 레일즈 콘솔의 이전 단계에서 작성한 단계를 시도해보고 실제 문제가 무엇인지 확인하십시오. –

0

@client 개체에서 빌드가 완료된 후 명시 적으로 저장을 호출해야하는 것 같습니다.

그렇지 않으면 ActiveRecord는 트랜잭션을 저장하지 않고 join_table에 새 레코드를 삽입합니다.

+0

업데이트 된 답변보기 –