在rails create action中将attributes设置为belongs_to属性

时间:2015-02-26 19:02:34

标签: ruby-on-rails refinerycms refinery

我正在尝试在我的创建操作中设置页面的标题。

我需要page.translation.title = params[:page][:title]

def create
  @page = Page.new(params[:page])
  @page.translation.title = params[:page][:title]
  if @page.save
    redirect_to admin_pages_path
   else
     render :new
   end
 end

也试过了 @translation = @page.translation.build(title: params[:page][:title])

我跑步时从控制台

p = Page.last
p.translation.title 
 => nil  -----> right now after its created, title is nil. 
p.translation.title = "foo"
 => "foo"

这就是我在创作中的作用。任何帮助都会很大  赞赏。谢谢。

更新:

我在一个在refinerycms 2.1.0.dev上运行的遗留应用程序上使用它

相关代码:

https://github.com/DynamoMTL/g-refinerycms/blob/244d4a89aef4ad31aed9c50a0ca4c8a2ffd3d1ac/pages/app/models/refinery/page_part.rb#L10

https://github.com/DynamoMTL/g-refinerycms/blob/244d4a89aef4ad31aed9c50a0ca4c8a2ffd3d1ac/pages/app/models/refinery/page.rb#L45-L49

https://github.com/DynamoMTL/g-refinerycms/blob/244d4a89aef4ad31aed9c50a0ca4c8a2ffd3d1ac/pages/app/models/refinery/page.rb#L11-L14

解决方案

def create
    @page = Refinery::Page.new(params[:page])

    if @page.save!
      @page.translations.create(slug: @page.slug,
                                title: params[:page][:title],
                                locale: params[:switch_locale])
      flash.notice = t(
            'refinery.crudify.created',
            what: "'#{@page.title}'"
          )
      redirect_to admin_pages_path
    else
      render :new
    end
  end

0 个答案:

没有答案