是否可以将数据插入一个控制器内的两个不同表中

时间:2019-05-24 21:56:13

标签: ruby-on-rails ruby ruby-on-rails-5

我有这个表,名字是

  
    

用户表

  

  
    

图片表

  

其主要工作是存储图片路径,名称和用户ID(这样做是因为我想允许我的应用程序的用户上传更多图片,如果我在其中为图片创建一列,用户表不允许我这样做。

现在在表单(注册表单)中,如果用户决定上传图片,我希望将图片保存在图片表中,而仍在其中

  
    

Users_controller创建方法

  

这是我到目前为止所做的(new.html.erb)

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <%= form_for(@user, url: signup_path) do |f| %>
          <%= render'shared/error_messages', object: f.object %>
          <%= f.label :name %>
          <%= f.text_field :name, class: 'form-control' %>

          <%= f.label :email %>
          <%= f.email_field :email, class: 'form-control' %>

          <%= f.label :username %>
          <%= f.text_field :username, class: 'form-control' %>

          <%= f.label :password %>
          <%= f.password_field :password, class: 'form-control' %>

          <%= f.label :password_confirmation, "Confirmation" %>
          <%= f.password_field :password_confirmation, class: 'form-control' %>

          <span class="picture">
            <%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>
          </span>
          <%= f.submit "Create an account", class: "btn btn-primary" %>
        <% end %>
    </div>
</div>

在用户控制器中,我在create方法中有此

1. def create
2.  @user = User.new(user_params) # Not the final implementation!
3.
4.  if @user.save
5.      # Save to the picture name to the picture table
6.               if params[:picture].present?
7.                 # How do I save the picture to the picture table from users controller
8.            @user.send_activation_email
9.        flash[:info] = "Please check your email to activate your account."
10.       redirect_to root_url
11. else
12.     #@states = State.all
13.         render 'new'
14. end
15.  end

如果您看第6行和第7行,我有这些

if params[:picture].present?
  # How do I save the picture to the picture table from users controller

这就是现在的问题所在,如何将图片名称插入到user_controller内部的数据库中

2 个答案:

答案 0 :(得分:1)

# new action
def new 
  @user = User.new
  @user.pictures.build
end

# create action
def create
  @user = User.new(user_params)
  @user.save
end

private
def user_params
  params.require(:user).permit(:name, pictures_attributes: [:id]) 
# in addition to the id you need to specify the other required fields.
end
# User model
class User
  has_many :pictures
  accepts_nested_attributes_for :pictures, allow_destroy: true
end
# form view

<%= form_for @user do |f| %>
  pictures:
    <%= f.fields_for :pictures do |picture_form| %>
    # your code

我希望这会帮助您理解

答案 1 :(得分:0)

我认为您正在寻找的是嵌套表格。 嵌套表单也接受子类的参数,并且在视图中您可以添加任意数量的图像,并将其存储在其各自的表中。 签出-https://github.com/ryanb/nested_form