2011-11-07 9 views
0

これは私のアプリ/コントローラ/ categories_controller.rbで発生します。3:` create ' ブログを開発し、マイクロポスト。したがって、各マイクロポストは1つのカテゴリのみを持つことができます。私は3つのテーブル:ユーザー、micropostsとカテゴリがあります。私の意図は、ユーザープロフィールページでカテゴリーを追加させることです。#<ユーザー:0x00000103047730>のための定義されていないエラーのメソッド `categories:

model/category.rb 
class Category < ActiveRecord::Base 
    belongs_to :user  
    attr_accessible :category 
end 

モデル/ user.rb

has_many :category, :dependent => :destroy 
accepts_nested_attributes_for :category, :reject_if =>lambda {|a| a[:category].blank?} 

categoriesController

class CategoriesController < ApplicationController 
def create 
    @category = current_user.categories.new(params[:category]) 
    if @category.save 
     flash[:success] = "Category created!" 
     redirect_to @user 
    else 
     flash[:error] = "Category not created." 
     render @user 
    end 
    end 
end 

がUserController

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

ユーザshow.html

モデルで
<%= form_for @category do |f|%> 
     <%= hidden_field_tag :user_id, @user.id %> 
     <%= f.label :category ,"Category:"%> 
     <%=h f.text_field :category %><br /> 
     <%= f.submit "Add Category" %> 
<% end %> 

答えて

4

あなたは関係

has_many :category 

を持っている。しかし、コントローラにIES

current_user.categories 

has_many :categoriesにリレーション名の名前を変更し、ユーザーcategorから取得します。

+0

has_many:カテゴリ複数である必要があります – Pavel

+0

ありがとうございます!出来た!私は、モデルとコントローラーで複数形や単数形を使うべきな時はちょっと混乱します。 –

関連する問題