有人可以帮我联系吗

时间:2019-04-29 19:57:39

标签: ruby-on-rails associations

我正在尝试设置一个具有工作板功能的简单Rails应用程序。我能够将作业添加到数据库,直到在作业模型和设计用户模型之间添加了关联。现在,当我填写表格时,它不会更新数据库。

jobs_controller

class JobsController < ApplicationController
  def index
    @jobs = Job.all
  end

  def new
    @job = Job.new
  end

  def listing
  end

  def listings
  end

  def create

    @job = Job.new(params.require(:job).permit(:title, :description, :url, :user_id))

    if @job.save
      redirect_to root_path
    else
      render "new"
    end
  end
end

new.html.erb

<%= simple_form_for @job do |form| %>
  <%= form.input :title, label: "Job title" %>
  <%= form.input :description, label: "Description" %>
  <%= form.input :url, label: "URL" %>
  <%= form.button :submit %>
<% end %>

index.html.erb

<% @jobs.each do |job| %>
  <div class="job">
    <h2><%= link_to job.title, job.url %></h2>
    <p><%= job.description %></p>
  </div>
<% end %>
<p><%= link_to "Add a job", new_job_path %></p>

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :jobs
end

job.rb

class Job < ApplicationRecord
    belongs_to :user

end

控制台中没有错误,但是数据库似乎未更新或未更新视图。

我还进行了迁移:

class AddUserToJob < ActiveRecord::Migration[5.2]
  def change
    add_reference :jobs, :user, foreign_key: true
  end
end

2 个答案:

答案 0 :(得分:1)

如果您不想立即将作业与用户关联,则需要将关联更改为可选,例如:

class Job < ApplicationRecord
  belongs_to :user, optional: true
end

否则,您需要在表单中提供user_id或在控制器操作中进行设置。


您还应该将此部分委派给单独的方法

def job_params
  params.require(:job).permit(:title, :description, :url, :user_id)
end

Job.new(job_params)

答案 1 :(得分:1)

您可以在Devise中使用current_user来吸引用户。

class JobsController < ApplicationController
  # This restricts the actions to authenticated users and prevents a nil error
  before_action :authenticate_user, except: [:show, :index]

  # ...

  def create
    # this sets the user_id column
    @job = current_user.jobs.new(job_params)
    if @job.save
      # you really should set a flash message or something to notify the user
      # and possibly redirect to the show or index action instead
      redirect_to root_path
    else
      render "new"
    end
  end

  private 
  def job_params 
    params.require(:job)
          .permit(:title, :description, :url, :user_id)
  end
end