创建了新实例并将其保存到数据库

创建了新实例并将其保存到数据库

本文介绍了Rails 4:创建了新实例并将其保存到数据库,但未在视图中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的Rails 4应用程序中,有四个模型:

In our Rails 4 app, there are four models:

class User < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :calendars, through: :administrations
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Calendar < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :users, through: :administrations
end

class Post < ActiveRecord::Base
    belongs_to :calendar
end

以下是相应的迁移:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.integer :total_calendar_count
      t.integer :owned_calendar_count

      t.timestamps null: false
    end
  end
end

class CreateAdministrations < ActiveRecord::Migration
  def change
    create_table :administrations do |t|
      t.references :user, index: true, foreign_key: true
      t.references :calendar, index: true, foreign_key: true
      t.string :role

      t.timestamps null: false
    end
  end
end

class CreateCalendars < ActiveRecord::Migration
  def change
    create_table :calendars do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
        t.references :calendar, index: true, foreign_key: true
        t.date :date
        t.time :time
        t.string :focus
        t.string :format
        t.string :blog_title
        t.text :long_copy
        t.text :short_copy
        t.string :link
        t.string :hashtag
        t.string :media
        t.float :promotion
        t.string :target
        t.integer :approval
        t.text :comment

      t.timestamps null: false
    end
  end
end

我们具有以下表单来创建帖子:

We have the following form to create posts:

<h2>Create a new post</h2>
<%= form_for(@post) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
    <tr>
        <td class="field"><%= f.date_field :date, placeholder: "When do you want to publish this post?" %></td>
        <td class="field"><%= f.time_field :time, placeholder: "What time do you want to publish this post?" %></td>
        <td class="field"><%= f.text_field :focus, placeholder: "What is this post about?" %></td>
        <td class="field"><%= f.text_field :format, placeholder: "What type of post is this?" %></td>
        <td class="field"><%= f.text_field :blog_title, placeholder: "If this post is about a blog post, what is the title of the blog post?" %></td>
        <td class="field"><%= f.text_area :long_copy, placeholder: "What is the copy of the post?" %></td>
        <td class="field"><%= f.text_area :short_copy, placeholder: "What is the short copy of the post (to be used on Twitter for instance)?" %></td>
        <td class="field"><%= f.url_field :link, placeholder: "Which link to you want to embed in this post?" %></td>
        <td class="field"><%= f.text_field :hashtag, placeholder: "Which hashtag(s) do you want to you in this post?" %></td>
        <td class="field"><%= f.text_field :media, placeholder: "Which media file (image, video) do you want to include in this post?" %></td>
        <td class="field"><%= f.number_field :promotion, placeholder: "What advertising budget should be allocated to this post?" %></td>
        <td class="field"><%= f.text_field :target, placeholder: "Who do you want to target with this post?" %></td>
        <td class="field"><%= f.select(:approval, %w[Approved Needs edits To be deleted], {prompt: 'How does this post look?'}) %></td>
        <td class="field"><%= f.text_area :comment, placeholder: "Any comment?" %></td>

        <td><%= f.submit "Create", class: "btn btn-primary" %></td>

    </tr>

<% end %>

此表单已嵌入到Calendars#Show视图中,因此一旦创建了帖子,它就会出现在相应的日历中.

This form is embedded into the Calendars#Show view, so that as soon as a post is created, it appears in the corresponding calendar.

编辑2 :这是ou PostsController:

class PostsController < ApplicationController

  def create
    @post = Post.create!
    if @post.save
      redirect_to root_url
    else
      render root_url
    end
  end

end

当前,每当我们提交表单时,实际上都会创建一个帖子(我们通过控制台进行了检查).

Currently, whenever we submit the form, a post is actually created (we checked through the console).

编辑:实际上,新的@post已创建并保存到数据库,但所有值均设置为nil.似乎我们也存在将数据从表单保存到数据库中的问题.

EDIT: Actually, the new @post is created and saved to the database but all values are set to nil. It seems we also have a problem with the saving of data from the form and into the database.

但是,它没有出现在相应的日历中.

However, it does not appear in the corresponding calendar.

我们认为,这是由于以下事实:在创建帖子时,活动日历(其中嵌入了表单的日历)的calendar_id不会添加到新的帖子实例中.

We believe this is due to the fact that, when a post is created, the calendar_id of the active calendar (the one in which the form is embedded in) is not added to the new post instance.

但是,我们不知道如何实现它:

However, we don't know how to implement it:

  • 我们应该创建一个active_calendar方法,然后使用该方法自动将活动日历的active_calendar id分配给新创建的@post吗?
  • 我们是否应该在发布控制器或发布模型中简单地将活动日历id声明为变量,以便在创建新的@post时将其添加?
  • 我们是否应该通过表单中的隐藏字段将活动日历id包括在新创建的@post中?
  • Should we create an active_calendar method and then use it to automatically assign the active_calendar id of the active calendar to the newly created @post?
  • Should we simply declare the active calendar id as a variable, either in the post controller or the post model, so that we can add it when a new @post is created?
  • Should we include the active calendar id in the newly created @post through a hidden field in the form?

我们在这里碰壁,不确定自己在做什么错.

We kind of hit a wall here and are not sure of what we are doing wrong.

关于如何解决此问题的任何想法?

Any idea of how to fix this?

更新:如@ Fire-Dragon-DoL在其答案的注释中所建议,我们将使用一个隐藏字段.

UPDATE: as suggested by @Fire-Dragon-DoL in the comments of his answer, we are going to use a hidden field.

以下代码可以工作吗?

<td type="hidden" value="#{@calendar.id}"><% f.number_field :calendar_id %></td>

推荐答案

我不确定活动日历"信息的存储方式或存储位置,您肯定需要它.将其设置为User的字段,这是一个不错的选择.

I'm not sure how or where is stored your "active calendar" information, you definitely need it. Make it a field for User, it's a good option.

然后我将创建一个像这样的应用程序控制器方法

Then I would create an application controller method like

def active_calendar
  # Assuming you have a method to return current logged in user
  current_user.try(:active_calendar)
end

然后,在创建帖子时,您可以轻松地执行以下操作

Then when creating post you can easily perform the following

attrs = post_params.merge(calendar: active_calendar)
@post = Post.new(attrs)
# Or whatever logic you want
@post.save

仅当允许用户指定与活动日历不同的日历时,才使用隐藏字段,否则可能只是一个安全漏洞

Use the hidden field only if user is allowed to specify different calendars than the active one, otherwise it might just be a security hole

请注意,我编写的代码也是不安全的

这篇关于Rails 4:创建了新实例并将其保存到数据库,但未在视图中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:04