0

Я использую следующую форму и контроллер. Если я создам новое уведомление, все будет сохранено за исключением campus_id.Форма using collection_select, редактирование действия работает полностью, но не создает

Это, кажется, дает неправильный параметр кампуса, хотя я выбираю другой из раскрывающегося списка. Если впоследствии я отредактирую одну и ту же запись, она будет сохранена? Что происходит и как я могу это исправить?

Эта же форма используется для редактирования и создания действий. (частично)

Возможно, стоит отметить, что я использую мелкие маршруты для кампуса (has_many) и уведомлений (принадлежит_to).

routes.rb

shallow do 
    resources :campus do 
     resources :notifications 
    end 
    end 

Форма:

<%= form_for [@campus,@notification] do |f| %> 
    <% if @notification.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@notification.errors.count, "error") %> prohibited this notification from being saved:</h2> 

     <ul> 
     <% @notification.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :post %><br> 
    <%= f.text_area :post %> 
    </div> 
    <div class="field"> 
    <%= f.label :campus %><br> 
    <%= f.collection_select(:campus_id, Campus.all.order('name ASC'), :id, :name, prompt: true) %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

Это контроллер:

class NotificationsController < ApplicationController 
    before_action :set_notification, only: [:show, :edit, :update, :destroy] 
    before_action :set_campus, only: [:index, :new, :create] 

    def index 
    @notifications = @campus.notification 
    end 

    def show 
    end 

    def new 
    @notification = @campus.notification.new 
    end 

    def edit 
    end 

    def create 
    @notification = @campus.notification.new(notification_params) 

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

    def update 
    respond_to do |format| 
     if @notification.update(notification_params) 
     format.html { redirect_to @notification, notice: 'Notification was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: 'edit' } 
     format.json { render json: @notification.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    def destroy 
    @notification.destroy 
    respond_to do |format| 
     format.html { redirect_to campu_notifications_url(1) } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_notification 
     @notification = Notification.find(params[:id]) 
    end 

    def set_campus 
     @campus = Campus.find(params[:campu_id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def notification_params 
     params.require(:notification).permit(:post, :campus_id) 
    end 
end 

Если я смотрю на журнал я вижу неправильный параметр comitted.

работы POST "/ кампус/1/уведомлений" для 84.193.153.106 на 2014-09-29 18:29:33 +0000 Started POST "/ кампус/1/уведомлений" для 84.193.153.106 в 2014-09-29 18:29:33 +0000 Обработка NotificationsController # create as HTML Обработка по NotificationsController # create as HTML Параметры: {"utf8" => "_", "authenticity_token" => "oNSlEFeukwEj2hIAT89wFdIYwjHO5c8lzBlCqMyk31Y =", "уведомление" => {"post" => "sdqfdsfd", "campus_id" => "3"}, "commit" => "Создать уведомление", "campu_id" => "1"} Параметры: { msgstr "" ". lCqMyk31Y = ", " уведомление "=> {" post "=>" sdqfdsfd "," campus_id "=>" 3 "}, " commit "=>" Create Notification "," campu_id "=>" 1 "} Campus Load (0.4ms) SELECT «campus». * FROM «campus» WHERE «campus». «Id» = $ 1 LIMIT 1 [["id", "1"]] Campus Load (0.4ms) SELECT "campus ". * FROM " campus "WHERE" campus "." Id "= $ 1 LIMIT 1 [[" id "," 1 "]] (0.1ms) BEGIN (0.1ms) BEGIN SQL (28.6ms) INSERT INTO" « (« campus_id »,« created_at »,« post »,« updated_at ») ЗНАЧЕНИЯ ($ 1, $ 2, $ 3, $ 4) RETURNING« id »[[" campus_id ", 1], [" created_at ", Mon , 29 Sep 2014 18:29:34 UTC +00: 00], ["post", "sdqfdsfd"], ["updated_at", пн, 29 сен 2014 18:29:34 UTC +00: 00]] SQL (28.6ms) ВСТАВИТЬ В «уведомления» («campus_id», «created_at», «post», «updated_at») ЗНАЧЕНИЯ ($ 1, $ 2, $ 3, $ 4) RETURNING «id» [["campus_id", 1], ["created_at", Mon, 29 Sep 2014 18:29:34 UTC +00: 00], ["post", "sdqfdsfd"], ["updated_at", пн, 29 сен 2014 18:29:34 UTC +00: 00]] (3.5 мс) COMMIT (3.5ms) COMMIT

+0

Все выглядит правильно. Взгляните на свой журнал/development.log, отправив форму. Это может помочь! – Rodrigo

ответ

2

Может хотите изменить new и create действия, как это:

def new 
    @notification = @campus.notifications.build 
end 

def create 
    @notification = @campus.notifications.build(notification_params) 

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

campus.build_notification будет экземпляр уведомления о том, belongs_tocampus.Использование new потребует от вас пройти notification[campus_id] как часть ваших параметров.

+0

Я получаю неопределенный метод 'build_notification 'для ошибки # при попытке этого. – Christoph

+0

Я пробовал @ campus.notification.build, и у меня такая же проблема. – Christoph

+0

Неправильное направление ваших ассоциаций. Должно быть '@ campus.notifications.build' – sjaime

Смежные вопросы