【问题标题】:How do I build a request scheduler using ruby on rails?如何使用 ruby​​ on rails 构建请求调度程序?
【发布时间】:2013-06-18 02:57:43
【问题描述】:

我正在构建一个应用程序,该应用程序要求用户安排与导师的约会/对话时间。我很难建立这个。我一直在阅读 has_many :through => Association,但我知道我这样做是错误的。

在我的 User.rb 中

Class User < ActiveRecord::Base

  has_many :mentor_requests, foreign_key: "user_id"
  has_many :mentors, through: :mentor_requests

  def requested?(mentor) 
    mentor_requests.find_by_mentor_id(mentor.id)
  end

  def request!(mentor_request)
    mentor_requests.create!(mentor_request)
  end

  def unrequest!(mentor)
    mentor_requests.find_by_mentor_id(mentor.id).destroy
  end
end

在我的 Mentor.rb 中

class Mentor < User

  has_many :mentor_requests, foreign_key: "mentor_id"
  has_many :users, through: :mentor_requests
end

在 Mentor_request.rb 中

class MentorRequest < ActiveRecord::Base
  attr_accessible :reason, :mentor_id

  belongs_to :user, class_name: "User"
  belongs_to :mentor, class_name: "Mentor"

  validates :user_id, :mentor_id, presence: true 
  validates :reason, presence:true, length: { maximum: 140 }

  default_scope order: 'mentor_requests.created_at DESC'
end

在我的请求控制器中是

def create
  @mentor_request = current_user.mentor_requests.build(params[:mentor_request])
  #current_user.request!(@mentor)
  if @mentor_request.save
    flash[:success] = "Your request has been sent"
redirect_to user_path(current_user)
#Send confirmations to both user and mentor
#Send the notification to an internal message inbox
  else
render "new"
  end
end

当我转到位于导师请求/new.html.erb 的视图并尝试提交请求时,它说导师 ID 必须存在并且内容必须存在。我尝试使用来自导师显示页面的模式视图创建请求,但内容没有保存,我验证存在必须是真实的,然后当它重定向到导师_requests/new.html.erb 导师 ID 不再存在.

我不知道我是否提供了足够的信息,但我在这里非常需要帮助。如果我走在正确的道路上,我需要做什么才能让它发挥作用,如果这一切都错了,我该怎么做才能得到我想要的。

非常感谢

裘德

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3.2 rails-models


    【解决方案1】:

    让你的导师请求路由嵌套在导师之下。由于没有指导者的上下文,指导者请求是没有意义的,这是嵌套资源的最佳位置。

        resources :mentors do 
           resources :mentor_requests
        end
    

    这将使您的路线类似于 /mentors/1/mentor_requests

    然后在你的控制器中你也会有一个 params[:mentor_id] 所以让它

       def create
         @mentor_request = current_user.mentor_requests.build(params[:mentor_request])
         @mentor_request.mentor = Mentor.find(params[:mentor_id])
       end
    

    至于您的内容错误,这似乎是您没有填写的指导者请求所需的字段。您也需要将其传回并将其分配给指导者请求,或者如果您不填写,则取消验证'需要它

    【讨论】:

    • 非常感谢!这真的帮助了我,我已经为此工作了好几个星期并且不知道嵌套资源。你帮了我很多
    猜你喜欢
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多