neo
neo

Reputation: 4116

Set value to belongs_to attributes in rails create action

I'm trying to set the title of a Page in my create action.

I would need to 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

Also tried @translation = @page.translation.build(title: params[:page][:title])

from the console when I run:

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

This is what I what in my create action. any help would be greatly appreciated. Thank you.

Update:

I'm using this on a legacy application that's running on refinerycms 2.1.0.dev

Relevant code:

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

Solution

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

Upvotes: 1

Views: 43

Answers (0)

Related Questions