2017-04-04 6 views
1

사용자 (Devise 사용)가 확인란을 통해 여러 기본 설정을 지정한 다음 미리 정의 된 데이터의 라디오 버튼을 설정하는 페이지가 있습니다. 지금까지 사용자가 has_and_belongs_to_many 연관을 업데이트 할 수있게했지만 belongs_to가 작동하는 것을 얻을 수 없습니다.Rails에서 belongs_to 연관을 업데이트 할 수 없습니다.

PG::ForeignKeyViolation: ERROR: insert or update on table "users" violates foreign key constraint 

{"utf8"=>"✓", 
"_method"=>"patch", 
"user"=>{"sport_ids"=>["4"], "goal_ids"=>["6"], "moment_id"=>"moment_id", "workout_id"=>"workout_id"}, 
"commit"=>"Save Changes", 
"id"=>"1"} 

내가 통해 ID 번호를 통과 아니에요 것이 분명 보인다하지만 난 그것을 해결하는 방법을 알고하지 않습니다 내가 같이 다음과 같은 매개 변수와 함께이 오류가있어 순간

. 오류가 발생하지 않으면 아무 일도 일어나지 않습니다. 여기

모델/user.rb

class User < ApplicationRecord 
    belongs_to :city 
    belongs_to :workout 
    belongs_to :fitness_level 
    belongs_to :moment 

    has_and_belongs_to_many :sports 
    has_and_belongs_to_many :goals 
    has_and_belongs_to_many :gyms 
end 

컨트롤러/users_controller.rb

class UsersController < ApplicationController 

... 

def edit 
    @user = User.find(params[:id]) 
    @auth = current_user.id 

    # To make sure you can't edit someone elses profile 
    if @auth != @user.id 
     redirect_to @user 
    end 

    @sports = Sport.all.order(name: :asc) 
    @goals = Goal.all.order(name: :asc) 
    @workouts = Workout.all.order(:name) 
    @moments = Moment.all 

    end 

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

    if @user.update(user_params) 
     redirect_to @user 
    else 
     render 'edit' 
    end 
    end 

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

    private 

    def user_params 
    params.require(:user).permit(sport_ids: [], goal_ids: []) 
    params.require(:user).permit(:workout_id, :moment_id) 
    end 
end 

사용자/edit.html.erb 내 파일입니다

<%= simple_form_for @user do |f| %> 


# The following two work 
<% @sports.each do |sport| %> 
    <%= check_box_tag "user[sport_ids][]", sport.id, form.object.sports.include?(sport) %> 
    <%= sport.name %> 
    <% end %> 

<% @goals.each do |goal| %> 
    <%= check_box_tag "user[goal_ids][]", goal.id, form.object.goal.include?(goal) %> 
    <%= sport.name %> 
    <% end %> 

# the below doesn't work 

<% @moments.each do |moment| %> 

     <%= radio_button_tag 'user[moment_id]', :moment_id %> 

    <h4><%= moment.name %></h4> 

<% end %> <!-- end moments--> 

<% @workouts.each do |workout| %> 

     <%= radio_button_tag 'user[workout_id]', :workout_id %> 

<% end %> <!-- end workouts--> 
<% end %> <! -- end form --> 

나는 중요한 스타일링 재치가있다. h 태그를 사용하여 양식을 유지해야합니다.

편집 : 스키마에 추가 사용자 테이블

create_table "users", force: :cascade do |t| 
    t.string "email",     default: "", null: false 
    t.string "encrypted_password",  default: "", null: false 
    t.string "reset_password_token" 
    t.datetime "reset_password_sent_at" 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count",   default: 0, null: false 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.inet  "current_sign_in_ip" 
    t.inet  "last_sign_in_ip" 
    t.datetime "created_at",       null: false 
    t.datetime "updated_at",       null: false 
    t.jsonb "settings",    default: {}, null: false 
    t.string "first_name" 
    t.string "last_name" 
    t.date  "date_of_birth" 
    t.integer "city_id" 
    t.text  "bio" 
    t.integer "workout_id" 
    t.integer "fitness_level_id" 
    t.integer "moment_id" 
    t.index ["city_id"], name: "index_users_on_city_id", using: :btree 
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree 
    t.index ["fitness_level_id"], name: "index_users_on_fitness_level_id", using: :btree 
    t.index ["moment_id"], name: "index_users_on_moment_id", using: :btree 
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree 
    t.index ["settings"], name: "index_users_on_settings", using: :gin 
    t.index ["workout_id"], name: "index_users_on_workout_id", using: :btree 
    end 
+0

어떤 데이터베이스를 사용하고 있습니까? PostgreSQL? – Kavincat

+0

어이 postgres를 사용하고 있습니다 –

+0

사용자가 [% = radio_button_tag], [moment_id] [], moment.id %>'또는'<% = radio_button_tag '사용자 [moment_id]', moment.id %>' ? '사용자/edit.html.erb'에서 –

답변

1

임 그 라인의 확신 문제 :

<%= radio_button_tag 'user[moment_id]', :moment_id %> 

업데이트를 controller`s 할 수있는보기에서 moment_id 및 workout_id를 전달 해달라고 동작.

시도로 변경합니다 :

<% @moments.each do |moment| %> 

    <%= radio_button_tag 'user[moment_id]', moment.id %> 

    <h4><%= moment.name %></h4> 

<% end %> <!-- end moments--> 

같은이 운동입니다 : 한 줄에

또한
<% @workouts.each do |workout| %> 

     <%= radio_button_tag 'user[workout_id]', workout.id %> 

<% end %> <!-- end workouts--> 

이유를 허용 패스 해달라고 PARAMS? 이와 같이 :

def user_params 
    params.require(:user).permit(:moment_id, :workout_id, sport_ids: [], goal_ids: []) 
    end 
+0

params를 한 줄에 전달하면 구문 오류, 예기치 않은 ',', expecting => [], goal_ids : [], : moment_id, : workout_id)^ –

+0

그러나 두 줄 모두에서 작동하는 것 같습니다. 지금은 업데이트 중이지만 편집 페이지로 돌아갈 때마다 라디오 버튼이 선택되지 않아 사용자에게 아무런 문제가없는 것처럼 보입니다. (또한 정말 고마워, 시간) –

+0

@SamPrice 예, 내 잘못. 이것은 정확합니다.'params.require (: user) .permit (: moment_id, : workout_id, sport_ids : [], goal_ids : [])' –