【问题标题】:Ruby On Rails Using Active Record to associate objectsRuby On Rails 使用 Active Record 关联对象
【发布时间】:2012-02-24 00:05:54
【问题描述】:

我已经阅读了一些教程和一本关于使用 Active Record 的书,但是我无法将这些部分联系在一起。我使用 devise 创建了一个名为 User 的模型:

class User < ActiveRecord::Base
  has_many :tasks
  ....
end

我使用脚手架创建任务:

class Task < ActiveRecord::Base
  belongs_to :user#, :autosave => true

  validates_presence_of :description, :date
  validates_numericality_of :hours

  def add_user(creating_user)
    user << creating_user
  end
end

task_controller.rb

# POST /tasks
  # POST /tasks.json
  def create
    @task = Task.new(params[:task])

    # add in user to task
    @task.add_user current_user

    respond_to do |format|
      if @task.save
       .... #default code
      end
    end
  end

当我尝试保存任务然后通过视图抱怨对象为零时:

NoMethodError in TasksController#create

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<
Rails.root: /home/steven/csc309/project/Source/TPHNN

Application Trace | Framework Trace | Full Trace
app/models/task.rb:8:in `add_user'
app/controllers/tasks_controller.rb:48:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"zSslFLGZ+dbwr1+TBlUtq1F89chUtlBSV3qTHe6G0yY=",
 "task"=>{"id"=>"-4",
 "hours"=>"1",
 "miles"=>"2",
 "description"=>"dd",
 "date(1i)"=>"2012",
 "date(2i)"=>"2",
 "date(3i)"=>"23",
 "date(4i)"=>"23",
 "date(5i)"=>"34"},
 "commit"=>"Create Task"}
Show session dump

_csrf_token: "zSslFLGZ+dbwr1+TBlUtq1F89chUtlBSV3qTHe6G0yY="
session_id: "31e12032237fb42146b5291ab01cf71f"
warden.user.user.key: ["User", [1], "$2a$10$9P8RUZvg6r4LNSRy5FOdFu"]

感谢您的帮助

【问题讨论】:

    标签: ruby-on-rails activerecord devise


    【解决方案1】:

    关闭但不完全在那里!这可能是您想要的更多:

    class Task < ActiveRecord::Base
      belongs_to :user#, :autosave => true
    
      validates_presence_of :description, :date
      validates_numericality_of :hours
    
      def add_user(creating_user)
        user = creating_user
      end
    end
    

    或者您可以在控制器中简化事务并在其中一步完成所有操作:

    def create
      @task = current_user.tasks.new(params[:task])
    
      ...
    

    【讨论】:

    • 非常感谢您的帮助。 user = created_user 没有工作,但你建议做的“@task = current_user.tasks.new(params[:task])”工作得很好,谢谢。对于其他希望做我所做的事情以使这一切正常工作的人来说,我必须运行以下迁移:rails generate migration AddUserIdToTasks user_id:reference
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2010-12-06
    • 2017-10-14
    • 2014-12-06
    相关资源
    最近更新 更多