2

나는이 질문에 a github repo that you can find here을 만들었습니다. 나는 3 모델을 가지고있다 :레일에 많은 관계가 많은 best_in_place 4

class User < ActiveRecord::Base 
    has_many :user_countries 
    has_many :event_countries, 
    -> { where(user_countries: {:event => true}) }, 
    :through => :user_countries, 
    :source => :country 
    has_many :research_countries, 
    -> { where(user_countries: {:research => true}) }, 
    :through => :user_countries 
    :source => :country 
end 

class UserCountry < ActiveRecord::Base 
    belongs_to :country 
    belongs_to :user 
end 

class Country < ActiveRecord::Base 
    # ... 
end 

그래서 사용자는 event_countries와 research_countries를 선택할 수 있어야한다. 여기

class UsersController < ApplicationController 

    respond_to :html, :json 
    before_action :get_user, only: [:show, :edit, :update] 
    before_action :get_users, only: [:index] 

    def index 
    end 

    def show 
    end 

    def edit 
    end 

    def update 
    @user.update_attributes(user_params) 
    respond_with @user 
    end 

    private 

    def get_user 
    @user = User.find(params[:id]) 
    end 

    def get_users 
    @users = User.all 
    end 

    def user_params 
    params.require(:user).permit(:first_name, :event_countries => [:id, :name]) 
    end 
end 

그리고 내 사용자 쇼 페이지의 :

<%= best_in_place @user, :first_name %> 

<p> event countries: </p> 
<%= best_in_place @user, :event_countries, place_holder: "click here to edit", as: :select, collection: Country.all.map {|i| i.name} %> 

<%= link_to "users index", users_path %> 

그래서 정말 여기에 복잡 아무것도 없다가

여기 내 사용자 컨트롤러 (복잡한 아무것도)입니다. 또한 사용자 이름을 성공적으로 수정할 수 있으므로 best_in_place가 정상적으로 작동합니다.

질문 : event_countries는 어떻게 편집합니까? 당신이 볼 수 있듯이 나는 국가들과의 수집 옵션을 사용하려고했는데 내가 얻을 국가를 선택하려고 할 때 다음

Processing by UsersController#update as JSON 
    Parameters: {"user"=>{"event_countries"=>"3"}, "authenticity_token"=>"l5L5lXFmJFQ9kI/4klMmb5jDhjmtQXwn6amj1uwjSuE=", "id"=>"6"} 
    User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 6]] 
    (0.1ms) begin transaction 
    (0.1ms) rollback transaction 
Completed 500 Internal Server Error in 3ms 

NoMethodError (undefined method `each' for nil:NilClass): 
    app/controllers/users_controller.rb:17:in `update' 
나는 그것이 무엇을하고 있는지 이해하지

, 나는 그것이 문제가 될 수 있어야합니다 알고 컬렉션 옵션. 파일을 볼 필요가 있으면 여기에서 내 repo를 확인하십시오 : https://github.com/spawnge/best_in_place_join_models_twice. 내가 어떤 대답이/제안은 크게 감사하겠습니다 :)이 많은 시간을 보냈습니다


갱신 :

<%= best_in_place @user, :event_country_ids, as: :select, collection: Country.all.map { |i| i.name }, place_holder: "click here to edit", html_attrs: { multiple: true } %> 

내가 추가 한 :이 시도

: 내 사용자 PARAMS에 event_country_ids :

params.require(:user).permit(:first_name, :event_country_ids) 

그리고 지금은 모든 나라를 볼 수 있지만 내가 선택할 때 오 NE 여기에 내가 무엇을 얻을 :

Started PUT "https://stackoverflow.com/users/3" for 127.0.0.1 at 2014-12-18 01:19:27 +0000 
Processing by UsersController#update as JSON 
    Parameters: {"user"=>{"event_country_ids"=>"1"}, "authenticity_token"=>"aZAFIHgzdSL2tlFcGtyuu+XIJW3HX2fwQGHcB9+iYpI=", "id"=>"3"} 
    User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 3]] 
    (0.0ms) begin transaction 
    Country Load (0.0ms) SELECT "countries".* FROM "countries" WHERE "countries"."id" = ? LIMIT 1 [["id", 1]] 
    Country Load (0.0ms) SELECT "countries".* FROM "countries" INNER JOIN "user_countries" ON "countries"."id" = "user_countries"."country_id" WHERE "user_countries"."event" = 't' AND "user_countries"."user_id" = ? [["user_id", 3]] 
    SQL (0.1ms) DELETE FROM "user_countries" WHERE "user_countries"."user_id" = ? AND "user_countries"."country_id" = 2 [["user_id", 3]] 
    SQL (0.0ms) INSERT INTO "user_countries" ("country_id", "event", "user_id") VALUES (?, ?, ?) [["country_id", 1], ["event", "t"], ["user_id", 3]] 
    (20.9ms) commit transaction 
Completed 204 No Content in 28ms (ActiveRecord: 21.3ms) 

당신은 올바른 콘텐츠 삽입 것으로 보인다 볼 수 있듯이 : 난 그냥 그 후 완료 (204) 어떤 내용을 얻을 그러나 INSERT INTO "user_countries" ("country_id", "event", "user_id") VALUES (?, ?, ?) [["country_id", 1], ["event", "t"], ["user_id", 3]]을. 입력이 비어있는 페이지를 새로 고침 할 때 이해가 안됩니다. 어떠한 제안 ?


업데이트 2 :

내가 콘솔에서 확인하고 나는 사용자에게 event_countries를 추가 할 수 있습니다 작동합니다. 그러나 내가 페이지를 새로 고칠 때 사용자의 event_countries를 표시하지는 않습니다. 왜냐하면 내가 event_country_ids 개체를 사용하고 있기 때문입니다.

답변

2

나는 다음과 같은 코드가 작동해야한다고 생각 :

<%= best_in_place @user, :event_country_ids, as: :select, 
    collection: Country.all.each_with_object({}) { |i, memo| memo[i.id] = i.name }, 
    place_holder: "click here to edit", 
    html_attrs: { multiple: true } %> 

당신은 사용자가 여러 event_countries을 할당 할 수 있기를 원하는 가정.

+0

안녕하세요 @ 콜레 션 패스는 답변에 많은 감사를드립니다. 나는 당신이 말한 것과 똑같은 일을했지만 이상한 오류가 발생합니다 : 'syntax error, unexpected =>, expecting'} '... h_with_object ({}) {| i | i.id => i.name}, place_holder : "cli ... ... ^"솔직히 말하면 구문 오류가 예상되지 않았습니다. 무엇이 잘못 되었습니까? 그런데, [each_with_object 메서드 고맙습니다 다시 – bTazi

+0

이 질문에 그들은 each_with_index 메서드를 사용했습니다. 나는 그렇지 않습니다. (Rails 4에서 더 이상 사용되지 않습니다.) (http://apidock.com/rails/Enumerable/each_with_object)? 이것이 도움이 될 수 있는지 확인하십시오 : http://stackoverflow.com/questions/21184592/rails-4-best-in-place-gem-and-many-to-many-association – bTazi

+0

구문 오류로 불편을 끼쳐 드려 죄송합니다. 내 대답은 올바른 구문을 반영하기 위해뿐만 아니라 each_with_object에 대한 루비 핵심 설명서에 대한 링크를 제공합니다. 나는 확실히 루비 코어 라이브러리에 있기 때문에 당신이 제공 한 링크에서 deprecated로 표시되었는지 모르겠다. – ColetranePass