[英]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 請求。 在此之前,我認為Profile
和User
之間應該存在一種關系,例如User has_one Profile
和Profile 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 Job
對Successfully Applied
。 我沒有處理上面的任何錯誤,因此您可以根據需要進行操作,但這應該會讓您有一個基本的想法。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.