Соединение между тремя контроллерами - PullRequest
0 голосов
/ 02 марта 2012

У меня три контроллера - пользователи, истории, категории. Я хочу, когда я вошел в систему как администратор, чтобы создавать категории, а затем писать истории для каждой категории. Я выполнил часть задачи, но в БД в таблице Stories category_id пуст, и я не могу понять, как это исправить. Вот часть моего кода:

история / new.html.erb:

<%= form_for(@story) do |f| %>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :category %><br />
    <%= f.collection_select :category_id, @categories, :id, :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit "Add" %>
  </div>
<% end %>

stories_controller.rb:

class StoriesController < ApplicationController
  before_filter :admin_user

  def new
    @story = Story.new
    @categories = Category.all
    @title = "Add news"
  end

  def create
    @categories = Category.all
    @story = current_user.stories.build(params[:story])
    if @story.save
      flash[:success] = "Successfullly added news"
      redirect_to @story
    else
      @title = "Add news"
      render 'new'
    end
  end

  private

  def admin_user
    redirect_to(root_path) unless current_user.admin?
  end
end

story.rb:

class Story < ActiveRecord::Base
  attr_accessible :title, :content

  belongs_to :user
  belongs_to :category

  validates :title, :presence => true
  validates :content, :presence => true
  validates :user_id, :presence => true

  default_scope :order => 'stories.created_at DESC'
end

category.rb:

class Category < ActiveRecord::Base
  attr_accessible :title

  has_many :stories

  validates :title, :presence     => true,
            :length       => { :within => 6..40 }
end

user.rb:

class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :name, :email, :password, :password_confirmation

  has_many :stories

  validates :name,  :presence => true,
            :length   => { :maximum => 50 }
  validates :email, :presence => true

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :email, :presence   => true,
                :format     => { :with => email_regex },
                :uniqueness => true

  validates :password, :presence     => true,
                   :confirmation => true,
                   :length       => { :within => 6..40 }

  before_save :encrypt_password

  def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
  end

  def self.authenticate(email, submitted_password)
    user = find_by_email(email)
    return nil  if user.nil?
    return user if user.has_password?(submitted_password)
  end

  def self.authenticate_with_salt(id, cookie_salt)
    user = find_by_id(id)
    (user && user.salt == cookie_salt) ? user : nil
  end

  private

  def encrypt_password
    self.salt = make_salt unless has_password?(password)
    self.encrypted_password = encrypt(password)
  end

  def encrypt(string)
    secure_hash("#{salt}--#{string}")
  end

  def make_salt
    secure_hash("#{Time.now.utc}--#{password}")
  end

  def secure_hash(string)
    Digest::SHA2.hexdigest(string)
  end
end

1 Ответ

1 голос
/ 02 марта 2012

Вам необходимо добавить attr_accessible: category_id к вашей модели истории

Это предотвращает массовое назначение в вашем контроллере метод создания. В качестве альтернативы вы можете извлечь category_id из хеша params и назначить его в отдельной строке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...