f.association在simple_form CURRENT_USER

问题描述 投票:1回答:2

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

我试图连接一个新的“项目”与谁在创造它的特定用户的创建。要做到这一点,我传递的hidden valuecurrent_usersimple_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
ruby-on-rails devise
2个回答
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

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 }  %>
© www.soinside.com 2019 - 2024. All rights reserved.