Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamical attr_accessible attributes #18

Closed
HendrikRoth opened this issue Aug 9, 2013 · 5 comments
Closed

Dynamical attr_accessible attributes #18

HendrikRoth opened this issue Aug 9, 2013 · 5 comments

Comments

@HendrikRoth
Copy link

Instead of defining each several language for attr_accessible

class Product < ActiveRecord::Base
  attr_accessible :name_en, :name_de, :name_fr
  translates :name
end

it would be nice to set only one central attribute.

class Product < ActiveRecord::Base
  attr_accessible :name_translations
  translates :name
end

Is there a way to change this behavior?

@robworley
Copy link
Contributor

You can certainly do this and assign the name_translations hash directly. Does it work for your use case?

@HendrikRoth
Copy link
Author

Do you have an example?
Am 10.08.2013 14:26 schrieb "Rob Worley" notifications@github.com:

You can certainly do this and assign the name_translations hash directly.
Does it work for your use case?


Reply to this email directly or view it on GitHubhttps://github.com//issues/18#issuecomment-22438931
.

@HendrikRoth
Copy link
Author

robworley: my problem is the attr_accessible part. at the moment i have to add :name_en, :name_fr, etc.

Is there another way to have this dynamic for several locales?

@robworley
Copy link
Contributor

Sorry for the late response. Here's one way to do it:

class Product < ActiveRecord::Base
  I18n.available_locales.each { |locale| attr_accessible "name_#{locale}" }
  translates :name
end

Then in the view template:

<%= form_for @product do |f| %>
  <% I18n.available_locales.each do |locale| %>
    <%= f.label "name_#{locale}" %>
    <%= f.text_field "name_#{locale}" %>
  <% end %>
  <%= submit_tag %>
<% end %>

@isness
Copy link

isness commented Apr 18, 2016

 I18n.available_locales.each { |locale| attr_accessible "name_#{locale}" }

Is there a nice way to do this in Rails 4? I understand I have to list all fields as strong params, but I've been unable to find any nice looking solution if there are many locales and a lot of translated fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants