f。以simple_form

时间:2019-02-02 20:17:56

标签: ruby-on-rails devise

我正在建立一个网站,用户可以在其中创建一个包含多个“论文”的“项目”。

我正在尝试将新“项目”的创建与正在创建该项目的特定用户联系起来。为此,我将hidden value作为current_user传递到simple_form中。但是,我无法这样做,实际上该项目无法保存。 但是,如果我修改以下行:

<%= f.association :user, label: "Which user is creating it?",
:as => :hidden, :input_html => { :value => current_user }  %>

使用

        <%= f.association :user%>

它允许我在所有用户中进行选择,如果选择一个,它会创建“项目”。

因此下,我认为我的问题是我传递的方式,current_usersimple_form。我以这种方式通过:input_html => { :value => current_user }

_form_new.html.erb

  <%= current_user%> #IT DISPLAYS CORRETLY THE CURRENT USER

<div class="container">

  <div class="row ">
    <div class="col-sm-6 col-sm-offset-0">

<%= simple_form_for(@project) do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

      <div class="form-inputs">
        <%= f.input :title, label: "Write the title of the project you are creating" %>
        <%= f.input :body, label: "Write a short summary of the project you are adding", as: :text, input_html: {rows: 15, cols: 10} %>
        <%= f.association :user, :as => :hidden, label: "Which user is creating it?", :input_html => { :value => current_user }  %>

      </div>

      <div class="form-actions">
        <%= f.button :submit %>
      </div>
      <% end %>
    </div>
  </div>
</div>

User.rb

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :projects
end

Project.rb

class Project < ApplicationRecord
  belongs_to :user
  has_many :papers
end

2 个答案:

答案 0 :(得分:1)

如果您通过current_user.id通过表单,即使在隐藏字段中,任何用户都可以更改它并为其他人创建项目。不知道是否想要。正确的方法是在控制器中调用current_user.projects.build

def create
  @project = current_user.projects.build(project_params)
  if @project.save
    redirect_to projects_path
  else
    render :new
end

答案 1 :(得分:0)

解决了!

我必须通过idcurrent user

正确的方法:

<%= f.input :title, label: "Write the title of the project you are creating" %>
<%= f.input :body, label: "Write a short summary of the project you are adding", as: :text, input_html: {rows: 15, cols: 10} %>
<%= f.association :user, label: "Which user is creating it?",
:as => :hidden, :input_html => { :value => current_user.id }  %>