2009-12-04 5 views
0

Я чрезвычайно новичок в рубине и программировании в целом. На этапе копирования, вставки и молитвы, как мне нравится называть ее. Я пытаюсь ограничить доступ к редактированию сообщений и комментариев создателю, но когда я создаю сообщение, user_id не заполняется в базе данных.Ruby on rails relationship

Заранее благодарим за помощь.

маршруты

map.resources :user_sessions 
map.resources :users 
map.resources :questions, :has_one => :user, :has_many => :answers 
map.login "login", :controller => "user_sessions", :action => "new" 
map.logout "logout", :controller => "user_sessions", :action => "destroy" 

модель пользователя

class User < ActiveRecord::Base 
    acts_as_authentic 
    has_many :questions 
    has_many :answers 
    end 

модель вопрос

class Question < ActiveRecord::Base 
    validates_presence_of :question, :tag 
    validates_length_of :question, :minimum => 5 
    validates_length_of :tag, :minimum =>4 
    belongs_to :user 
    has_many :answers 

end 

ответ модель

class Answer < ActiveRecord::Base 
    belongs_to :question 
    belongs_to :user 
end 

enter code here 

контроллер вопроса

class QuestionsController < ApplicationController 
    before_filter :find_question, 
    :only => [:show, :edit, :update, :destroy] 
    # GET /questions 
    # GET /questions.xml 
    def index 
    @questions = Question.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.xml { render :xml => @questions } 
    end 
    end 

    # GET /questions/1 
    # GET /questions/1.xml 
    def show 

    respond_to do |format| 
     format.html # show.html.erb 
     format.xml { render :xml => @question } 
    end 
    end 

    # GET /questions/new 
    # GET /questions/new.xml 
    def new 
    #@question = Question.new 
    @user = Question.new 
    end 

    # GET /questions/1/edit 
    def edit 

    end 

    # POST /questions 
    # POST /questions.xml 
    def create 
    @question = Question.new(params[:question]) 
    #@question = Question.user.new(params[:question]) 
     if @question.save 
     flash[:notice] = 'Question was successfully created.' 
     redirect_to(@question) 
     else 
     render :action => "new" 
     end 
    end 
    end 

    # PUT /questions/1 
    # PUT /questions/1.xml 
    def update 
     if @question.update_attributes(params[:question]) 
     flash[:notice] = 'Question was successfully updated.' 
     redirect_to(@question) 
     else 
     render :action => "edit" 
     end 
    end 

    # DELETE /questions/1 
    # DELETE /questions/1.xml 
    def destroy 
    @question.destroy 
    redirect_to(questions_url) 
    end 

    private 
    def find_question 
     @question = Question.find(params[:id]) 
    end 

контроллер Ответа

class AnswersController < ApplicationController 
    def index 
    @question = Question.find(params[:question_id]) 
    @answer = @question.answers 
    end 

    def show 
    @question = Question.find(params[:question_id]) 
    @answer = @question.answers.find(params[:id]) 
    end 

    def new 
    @question = Question.find(params[:question_id]) 
    #@question = Question 
    @answer = @question.answers.build 
    #@answer = Answer.new 
    #redirect_to questions_url(@answer.question_id) 
    end 

    def create 
    #@question = Question.find(params[:question_id]) 
    # @question = Question 
    @answer = Answer.new(params[:answer]) 

    if @answer.save 
     redirect_to question_url(@answer.question_id) 
    else 
     render :action => "new" 
    end 
    end 

    def edit 
    @question = Question.find(params[:question_id]) 
    @answer = @question.answers.find(params[:id]) 
    end 

    def update 
    @question = Question.find(params[:question_id]) 
    @answer = Answer.find(params[:id]) 
    if @answer.update_attributes(params[:answer]) 
     redirect_to question_answer_url(@question, @answer) 
    else 
     render :action => "edit" 
    end 
    end 

    def destroy 
    @question = Question.find(params[:question_id]) 
    @answer = Answer.find(params[:id]) 
    @answer.destroy 

    respond_to do |format| 
     format.html {redirect_to @question} 
     format.xml {head :ok} 
    end 
    end 

end 

ответ

0

Вы должны размаха модели на связанный объект для ActiveRecord для заполнения внешних ключей. Это проще всего с помощью вспомогательного метода. Если вы хотите, чтобы рамки для пользователя:

Выдержки из одного из моих приложений с помощью Authlogic:

class ApplicationController < ActionController::Base 

    helper_method :current_user_session, :current_user 

    protected 

    def current_user_session 
    @current_user_session ||= UserSession.find 
    end 

    def current_user 
    @current_user ||= current_user_session && current_user_session.user 
    end 

end 

Затем вы можете, например, область видимости current_user.answers.build, или current_user.answers.find(params[:id]

В качестве ответов относятся пользователи и вопросы. Вам нужно будет установить область действия в зависимости от того, какой объект имеет наибольший смысл. Предполагая, что вы решили, что это объект пользователя, вам нужно установить question_id самостоятельно. Добавьте @answer.question = @question в действие вашего контроллера. Не вводите вручную внешние ключи. @answer.question_id = @question.id, когда ActiveRecord с радостью сделает это за вас.

0

У вас есть current_user, что проверка подлинность? Если нет, вам это нужно. Я не использовал AuthLogic, но должны быть хорошие учебники о том, как это сделать.

Предполагая, что у вас есть current_user, самое простое решение было бы сделать что-то вроде:

def create 
    @answer = Answer.new(params[:answer]) 
    @answer.user_id = current_user.id <--- add this line 

    if @answer.save 
     redirect_to question_url(@answer.question_id) 
    else 
     render :action => "new" 
    end 
    end 
+0

Вы можете совместить эти первые две строки с одним: 'current_user.answers.new (params [: answer])' –

+0

спасибо за быстрый ответ fellas. Я сосредоточен на части вопроса, чтобы начать. Я добавил current_user.questions.new (params [: question]) в методе создания, но я получаю «нулевой объект, когда вы этого не ожидали», на nil.save – cachesking

+0

неважно, что я его получил. Энди, ваша причина в том, что вызвало проблему nil.save. im используя @question, прежде чем я его инициализирую. Спасибо. – cachesking