簡體   English   中英

Has_many 通過關聯 - 查看? 控制器?

[英]Has_many through association - View? Controller?

我是 Rails 的新手,我正在構建一個應用程序,用戶配置文件可以在其中申請工作。 我通過關聯創建了一個 has_many。 但是我沒有找到定義控制器和視圖的方法。 這是我的代碼:

楷模:

class Profile < ActiveRecord::Base
  has_attached_file :profileimg, :default_url => ":style/profile-img.jpg"
  validates_attachment_content_type :profileimg, content_type: /\Aimage\/.*\Z/
  belongs_to :user

  has_many :relationships
  has_many :jobs, through: :relationships
end

class Job < ActiveRecord::Base
  belongs_to :employer

  has_many :relationships, dependent: :destroy
  has_many :profiles, through: :relationships


end

class Relationship < ActiveRecord::Base
  belongs_to :profile
  belongs_to :job
end

PS:我可以在 Rails 控制台上創建關系並且它可以工作。

我應該如何編寫我的 RelationshipsController? 以及如何在我的“工作”頁面上放置一個按鈕,以便 current_user.profile 可以申請該工作?

控制器只是app/controllers文件。 只需手動或使用 CLI 上的rails g controller Jobs添加jobs_controller.rb

視圖進入app/views/jobs/ 最好運行rails g scaffold Example以獲取完整的模型、控制器和視圖作為示例或完成教程。

您的視圖應顯示如下內容:

Job            Apply For This Job

Job創建一個成員路由,如下所示:

resources :jobs do
  member do
    post 'apply_for_job'
  end
end

當有人點擊Apply For This Job按鈕時,向上述路由發送 AJAX 請求。 在此之前,我認為ProfileUser之間應該存在一種關系,例如User has_one ProfileProfile belongs_to User 所以在jobs_controller創建一個動作:

def apply_for_job
  @job = Job.find params[:id] #This should be in a before_filter
  @profile = current_user.profile
  @profile.relationships.create(job: @job)
  respond_to do |format|
    format.js
  end
end

然后在views中創建一個視圖jobs文件夾apply_for_job.js.erb通過使相應的響應和例如像Apply For This JobSuccessfully Applied 我沒有處理上面的任何錯誤,因此您可以根據需要進行操作,但這應該會讓您有一個基本的想法。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM