2014-09-19 3 views
0

레일을 처음 사용하기 때문에 중첩 된 형식과 그 모든 문제가 있습니다. 사용자 모델과 조직 모델이 있습니다. 사용자를 만들려면 그가 어떤 조직에서 왔는지 지정하고 싶습니다. 조직 이름이 이미 데이터베이스에 있거나, 그렇지 않은 경우 새 레코드를 만들고 해당 레코드를 사용자 모델과 연결하려고합니다.rails 자동 기록 exising 기록을 사용하는 방법

레일 프레임 워크에서 모든 관계 (다 대다 등)의 의미를 이해하는 데 어려움이 있지만 지금까지이 문제를 해결했습니다. 이에서

class User < ActiveRecord::Base 
    belongs_to :organization 
    accepts_nested_attributes_for :organization 
    ##### 
end 

는 콘솔에, 나는 사용자를 작성하고 지정할 수 있습니다 (짧은)과 조직

모델/organization.rb

class Organization < ActiveRecord::Base 

    has_many :user 

    validates_presence_of :name 


end 

모델/user.rb 이름을 입력하면 사용자에 대한 새 레코드와 조직에 대한 새 레코드가 만들어집니다. 문제는 때마다 이 새로운 조직을 생성한다는 것입니다.

기존 조직을 새 사용자와 연결할 수 있기를 원합니다. 양식의 typeahead.js와 같은 조직 목록을 얻을 수 있으므로 사용자가 하나를 선택할 때 이름이 동일합니다. 그러나 두 가지 (새로 생성 된 사용자와 이미 존재하는 조직)를 연관시키는 방법을 모르겠습니다.

조직의 ID에 숨겨진 필드를 넣고이 ID가 있는지 컨트롤러에 체크인하는 방법을 생각했습니다. 존재하는 경우 새로운 ID를 작성하지 않으면이 ID를 넣으십시오. 그러나 나는 이것을 어떻게하는지 모른다. 내가 존재하는 ORGANIZATION_ID = 3, 예를 들어, 사용자의 속성을 업데이트 콘솔에서 :

u.update_attributes(:organization_attributes => { id: 3 }) 

그것은 그가 ID를 가진 사용자를 찾을 수 없습니다 = ... 조직으로 말을 거부합니다. id = 3 ... 이해가 안됩니다.

나는 이것이 일반적인 경우이기 때문에 쉽게 생각할 수 있지만 내 머리를 망치고 있다고 생각합니다.

누군가가 나에게 설명 할 의사가 있다면 매우 감사 할 것입니다.

감사합니다.

편집 방금 ​​컨트롤러에서 뭔가를 시도했지만 작동하지 않습니다.

def create 

    @user = User.new(user_params) # :user object built from user inputform   
    org = Organization.find_by(name:user_params[:organization_attributes][:name]) 
    if org 
     @user.organization.id = org.id 
    end 
    if @user.save 
     # signin the user (token etc) 
     sign_in @user 
     flash[:success] = "Registration sucessfull !" 
     redirect_to @user 
    else 
     render 'new' 
    end 
end 

+ user_controller (강한 PARAMS)

def user_params 
    params.require(:user).permit(:lname,:email,:fname,:password,:password_confirmation, 
           :gender,:role,:display_private,:link_li,:country,:city,:phone,:hobbies, 
           :avatar,:org_name, :organization_attributes => [ :id, :name]) 
end 

+ form.html.ERB

<%= u.fields_for :organization do |o| %> 
           <%= o.label "Organization" %> 
           <!-- PUT ORGA --> 
           <%= o.text_field :name, class:"form-control" %> 
<% end %> 
+0

그것은'has_many해야한다 : 사용자 조직' –

답변

1

나는이에 대한 사용자 지정 방법 작성합니다 : 당신이 가지고 있기 때문에, 지금 getter 및 setter 메소드를

#in User 
def organization_name 
    (org = self.organization) && org.name 
end 

def organization_name=(name) 
    if org = Organization.find_by_name(name) 
    self.organization = org 
    else 
    self.organization = Organization.create(:name => name) 
    end 
end 

(즉 떨어져 =에서 같은 이름을 가진 두 가지 방법, 당신이 사용자의 속성처럼 organization_name을 치료할 수)에 서명하고 입력이 @user.organization_name과 의지 C에서 현재 값을 얻을 것이다

f.input :organization_name 

같은 양식 필드에 넣어 모두 @user.organization_name=에 새 값이 입력되었습니다.

+0

그럼 내가 시도해 보자. =)하지만 편집을 끝냈다. 내 솔루션이 제대로 작동해야하지만 그렇지 않다. 내가 얻지 못하는 것이있다. – Nikkolasg

+0

그것은 perf 세상에! 감사 !! – Nikkolasg

0

먼저 모델에서 accepts_nested_attributes를 제거합니다. 그런 다음 컨트롤러에서이 같은 수행해야합니다/user.rb 앱에서/모델에서

def create 

    @user = User.new(user_params) # :user object built from user inputform   
    org = Organization.where(name: user_params[:organization_attributes][:name]).first || Organization.create(name: user_params[:organization_attributes][:name]) 
    @user.organization = org 

    if @user.save 
     # signin the user (token etc) 
     sign_in @user 
     flash[:success] = "Registration sucessfull !" 
     redirect_to @user 
    else 
     render 'new' 
    end 
end 
+0

이것을 시도하십시오. 방금 게시 한 컨트롤러 코드를 기반으로 편집했습니다. – spiria

+0

좋은 눈, .first.을 놓쳤습니다. – spiria

+0

기본적으로 컨트롤러에서했던 것과 같은 내용이지만 콘솔에서는 제대로 작동하지 않습니다. 더하기이 솔루션은 매번 새로운 조직 기록을 만들고 이전에 존재했던 것과 관련이 있다고 생각합니다. – Nikkolasg

0

을 users_controller.rb에서

def self.create(name, attribute1, ... ,organization) 
    user = User.new(:name => name, :atr_1 => attribute_1, ....:atr_n => attribute_n) 
    user.organization = organization 
    raise "user not created" if !user.save 
    user 
end 

def create 
    org = Organization.find params['organization'] #expecting the param to be Organization#id 
    user = User.create(params['name'], ..., org) 
    render :json => {:message => "user created"} 
end