2015-04-15 1 views
0

Я использую рубин на рельсах simple_form gem, который установлен правильно. У меня возникают проблемы с «create». Сохранение данных из формы в базу данных.Ruby on Rails простая форма gem форма не отправляет данные в базу данных

FYI: Коттедж - это ситуация, которая заслуживает поддержки сообщества.

Пользователи имеют много cotts и cotts, принадлежащих пользователям.

Я удалил все валидации и форма сохранит без данных. Я могу выводить информацию о пользователе на странице cott show, но данные cott не сохраняются.

Когда я добавить проверку, я получаю ошибку: Ситуация не может быть пустым Решение не может быть пустым Бойкот не может быть пустым Жертва не может быть пустым Нарушитель не может быть пустым

class Cott < ActiveRecord::Base 

    belongs_to :user 

    has_many :categorizations 
    has_many :types, :through => :categorizations 

    validates :situation, presence: true, length: {maximum: 255} 
    validates :solution, presence: true, length: {maximum: 255} 
    validates :boycott, presence: true, length: {maximum: 255} 
    validates :victim, presence: true, length: {maximum: 80} 
    validates :violator, presence: true, length: {maximum: 80} 
    default_scope -> { order(created_at: :desc) } 
end 

Котт контроллер

class CottsController < ApplicationController 
    before_action :logged_in_user, only: [:show, :edit, :update, :destroy] 


    def new 
    @cott = Cott.new 
    end 


    def create 
    @cott = current_user.cotts.build if logged_in? 
    respond_to do |format| 
     if @cott.save 
     format.html { redirect_to @cott, notice: 'Cott was successfully created.' } 
     format.json { render :show, status: :created, location: @cott } 
     else 
     format.html { render :new } 
     format.json { render json: @cott.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    private 


    def cott_params 
     params.require(:cotts).permit(:user_id, :situation, :solution, :boycott, :victim, :violator, :violator_address, :violator_emails) 
    end 

end 

пользователя контроллера

class UsersController < ApplicationController 
    before_action :logged_in_user, only: [:index, :edit, :update, :destroy] 
    before_action :correct_user, only: [:edit, :update] 
    before_action :admin_user,  only: :destroy 


    def new 
    @user = User.new 
    end 


    def create 
    @user = User.new(user_params) 
    respond_to do |format| 
     if @user.save 
     @user.send_activation_email 
     UserMailer.account_activation(@user).deliver_now 
     format.html { redirect_to root_url, notice: 'Please check your email to activate your account.' } 
     else 
     format.html { render :new } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
    end 


    private 

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


    def user_params 
     params.require(:user).permit(:name, :email, :password, :password_confirmation) 
    end 

    # Confirms a logged-in user. 
    def logged_in_user 
     unless logged_in? 
     store_location 
     flash[:danger] = "Please log in." 
     redirect_to login_url 
     end 
    end 
    # Confirms the correct user. 
    def correct_user 
     @user = User.find(params[:id]) 
     redirect_to(root_url) unless current_user?(@user) 
    end 

    # Confirms an admin user. 
    def admin_user 
     redirect_to(root_url) unless current_user.admin? 
    end 
end 

Форма

<%= simple_form_for(@cott, html: { class: 'form-horizontal'}) do |f| %> 
    <fieldset class="univ_padding action"> 

    <% if @cott.errors.any? %> 
     <div id="error_explanation" > 
      <h2><%= pluralize(@cott.errors.count, "error") %> prohibited this cott from being saved:</h2> 

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


<div class="col-md-7"> 
    <!-- proof --> 

    <!-- situation --> 
    <div class="form-group"> 
     <%= f.label :situation, label: false, class: " control-label" %><br> 
     <div class=""> 
     <%= f.input :situation, label: false, label: false, class: "form-control situaton_form_area" %> 
     <span class="help-block">Explain the situations</span> 
     </div> 
    </div> 
    <!-- solution --> 
    <div class="form-group"> 
     <div class=""> 
     <%= f.label :solution, label: false, class: " control-label" %><br> 

     <%= f.input :solution, label: false, class: "form-control situaton_form_area" %> 
     <span class="help-block">How can the violator fix this situation.</span> 
     </div> 

    <!-- boycott --> 
<div class=""> 
     <%= f.label :boycott, label: false, class: " control-label" %><br> 

     <%= f.input :boycott, label: false, class: "form-control situaton_form_area" %> 
     <span class="help-block">How do you suppose we boycott this violator.</span> 
     </div> 
    </div> 

    <!-- victim --> 
    <div class="form-group"> 
     <div class=""> 
     <%= f.label :victim, label: false, class: " control-label" %><br> 

     <%= f.input :victim, label: false, class: "form-control" %> 
     <span class="help-block">Who are the victims?</span> 
     </div> 


    <!-- violator name --> 

     <div class=""> 
     <%= f.label :violator, "Violator Name", label: false, class: " control-label" %> 

     <%= f.input :violator, label: false, class: "form-control" %> 
     <span class="help-block">Violator name or business name</span> 
     </div> 
    </div> 

    <!-- violator address --> 
    <div class="form-group"> 
     <div class=""> 
     <%= f.label :violator_address, "Violator Addresss", label: false, class: " control-label" %> 

     <%= f.input :violator_address, label: false, class: "form-control"%> 
     <span class="help-block">Do you have an address for this violator?</span> 
     </div> 

    <!-- violator email --> 

     <div class=""> 
     <%= f.label :violator_email,"Violator Email", label: false, class: "control-label" %> 
     <%= f.input :violator_email, label: false, class: "form-control" %> 
     <span class="help-block">Email address of the violator.</span> 
     </div> 
    </div> 

    </div> 
    <div class="col-md-5"> 
     <!-- Multiple Checkboxes --> 
     <div class=""> 
     <%= f.label :types, "Chosee a Category", label: false, class: " control-label" %> 
     <%= f.association :types, as: :check_boxes, label: false, class: "form-control" %> 

     </div> 

    </div> 
    <!-- end Health & Safety --> 

    <div class="form-group"> 
     <div class="col-md-12 "> 
     <%= f.submit "submit cott", label: false, class: "btn btn-block btn-primary btn-large" %> 
     </div> 
    </div> 
</div 
    </fieldset> 
    <% end %> 

ответ

2

Проблема с создания метода вашего Cotts контроллера, вы не прошли Params, где вы строите свой объект. поэтому ваш объект пытается быть сохранен как пустой, и он возвращает ошибки проверки. Передайте сильные параметры, как показано ниже:

def create 
    @cott = current_user.cotts.build(cott_params) if logged_in? 
    respond_to do |format| 
     if @cott.save 
     format.html { redirect_to @cott, notice: 'Cott was successfully created.' } 
     format.json { render :show, status: :created, location: @cott } 
     else 
     format.html { render :new } 
     format.json { render json: @cott.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

Надеюсь, это поможет. сообщите мне, работает ли это или нет. Спасибо

+0

Я действительно имел это. Я отлаживал еще одну проблему, и я удалил параметр. :) но спасибо Rails Guy –

+0

No Worries @LeslyRevenge :) –