如何将作业分配给船只作为多对多关系

时间:2017-05-04 20:45:00

标签: ruby-on-rails ruby

我有一个航运项目,我可以在那里创建船只和工作。我与工作和船只有多对多的关系,但我在为船舶创造新工作时遇到了麻烦。

我想要一个新的链接,通过复选框为特定船只分配作业,但是当没有路线匹配get "/ship/all_jobs"时点击链接分配作业时,我收到错误。

这是我的船型:

class Ship < ApplicationRecord

  has_and_belongs_to_many :jobs

  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

  validates :name, uniqueness: true

end

这是我的工作模式:

class Job < ApplicationRecord
  has_and_belongs_to_many :ships

  validate :price_has_to_be_greater_than_minimum
  validates :title, uniqueness: true
  validates :description, length: { minimum: 50 }

  def price_has_to_be_greater_than_minimum
    errors.add(:cost, "price has to be greater than 1000") if
    !cost.blank? and cost > 1000
  end
end

这是Jobship连接表:

class Jobship < ApplicationRecord
  belongs_to :ships
  belongs_to :jobs
end

和我的船只控制员:

def all_jobs
  @ship = Ship.find(params[:id])
end

def create
  @ship = Ship.new(ship_params)
  if @ship.save
    flash[:notice] = 'Ship record was successfully created.'
    redirect_to(@ship)
  else
    render :action => "new"
  end
end

def save
  @ship = Ship.find(params[:id])
  @job = Job.find(params[:job])
  if params[:show] == "true"
    @ship.jobs << @ship
  else
    @ship.jobs.delete(@ship)
  end
  @ship.save!
  render :nothing => true
end

private

def ship_params
  params.require(:ship).permit(:name, :location, :avatar)
end
end

这是all_jobs视图:

<h1>jobs for <%= @ship.name %></h1>

<table>
  <tr>
    <th>assignl</th>
    <th>job</th>
  </tr>


  <%= form_for (@ship) do |f| %>
    <%= f.label "jobs" %><br />
    <%= f.collection_check_boxes :job_ids, Job.all, :id, :title do |b| %>
      <div class="collection-check-box">
        <%= b.check_box %>
        <%= b.label %>


       <%= f.submit %>
    <%end%>
  <%end%>

这是索引视图中所有作业的链接:

<%= link_to 'New ship', new_ship_path %>
<% @ships.each do |ship| %>
  <h1>ship name</h1><%=ship.name%><h1> ship location</h1>   <%= ship.location %>    <%= link_to 'Show', ship %>

  <%= link_to 'jobs',   ship_all_jobs_path(ship) %>
  <%= link_to "all jobs", jobs_path %>
<% end %>

我的路线:

Rails.application.routes.draw do

  devise_for :users
  resources :ships
  resources :jobs

  root :to => "ships#index"

  post "ship/all_jobs", :to=> "ships#save"

  get "ship/all_jobs/:id", :to => "ships#all_jobs"
end

1 个答案:

答案 0 :(得分:0)

首先,你对rails中的Task关系出错了,你不需要为联接表提供单独的模型,活动记录会在这里阅读http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association来学习更多;所以你不需要many to many模型。

Jobship

在定义路线之前,您必须先放置class Jobship < ApplicationRecord belongs_to :ships belongs_to :jobs end

/

您也可以在命令行中使用Rails.application.routes.draw do devise_for :users resources :ships resources :jobs root :to => "ships#index" post "/ship/all_jobs", :to=> "ships#save" get "/ship/all_jobs/:id", :to => "ships#all_jobs" end 查看已定义的路由。