Rails - Has_many通过 - 新建,保存和创建

时间:2014-11-20 22:12:29

标签: ruby-on-rails ruby-on-rails-4

我在Rails中通过关系遇到has_many问题。我检查了Rails指南,但是他们在视图中的控制器中的has_many效果文档很差。

以下是我的模特:

class Project < ActiveRecord::Base
  has_many :twitter_memberships
  has_many :twitter_accounts, through: :twitter_memberships
end

class TwitterAccount < ActiveRecord::Base
  has_many :twitter_memberships
  has_many :projects, through: :twitter_memberships
end

class TwitterMembership < ActiveRecord::Base
  belongs_to :project
  belongs_to :twitter_account
end

并且路线文件=&gt;

resources :projects do
  resources :twitter_accounts
end

现在我可以在没有任何错误的情况下从控制台测试关系:

Project.first.twitter_accounts
Project.first.twitter_memberships
TwitterAccount.first.twitter_memberships
TwitterAccount.first.projects

我也可以创建记录,完全正常:

Project.first.twitter_accounts.create(name: "bar")

创建正确的twitter_account和twitter_membership数据:

SQL (0.5ms)  INSERT INTO "twitter_accounts" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", Thu, 20 Nov 2014 22:01:06 UTC +00:00], ["name", "test_record"], ["updated_at", Thu, 20 Nov 2014 22:01:06 UTC +00:00]]

SQL (0.3ms)  INSERT INTO "twitter_memberships" ("created_at", "project_id", "twitter_account_id", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Thu, 20 Nov 2014 22:01:06 UTC +00:00], ["project_id", 1], ["twitter_account_id", 8], ["updated_at", Thu, 20 Nov 2014 22:01:06 UTC +00:00]]

到目前为止,所有代码和控制台操作都运行正常。我使用上面的命令成功创建了TwitterAccount和TwitterMembership。但是我对控制器和视图感到困惑。在此网址中:

http://foobar.com/projects/my-first-project/twitter_accounts/new

我有这样的表格:

<%= simple_form_for [@project, @twitter_account], :html => { :class => 'form-horizontal' } do |f| %>
  <%= f.text_field :name, :class => 'text_field' %>
  <%= f.text_field :account_id, :class => 'text_field' %>
  <%= f.submit nil, :class => 'btn btn-primary' %>
<% end %>

和app / controllers / twitter_accounts_controller.rb文件=&gt;

class TwitterAccountsController < ApplicationController
  before_action :set_project
  before_action :set_twitter_account, only: [:show, :edit, :update, :destroy]

  def new
    @twitter_account = @project.twitter_accounts.new
  end

  def create
    @twitter_account = @project.twitter_accounts.new(twitter_account_params)
    @twitter_account.save
  end

  private
    def set_project
      @project = Project.friendly.find(params[:project_id])
    end

    def set_twitter_account
      @twitter_account = TwitterAccount.friendly.find(params[:id])
    end

    def twitter_account_params
      params.require(:twitter_account).permit(:name, :account_id)
    end
end

当我提交此表单时,它只会创建&#34; TwitterAccount&#34;并没有创建&#34; TwitterMembership&#34;。我无法理解为什么它只是在创建&#34; TwitterAccount&#34;而不是创建&#34; TwitterMembership&#34;太。

正如我之前解释过的,我能够在Rails控制台中使用单个命令创建它们:

Project.first.twitter_accounts.create(name: "bar")

您能否通过关系解释我在has_many中创建和编辑对象的详细信息,并回答下面的问题。

提前致谢。

0 个答案:

没有答案