开发者

Rails 3 - A better way... i'm a newbie!

Please, can you suggest me a better way to accomplish this:

@infos = @activity.infos
@infos.each do |info|
  @activity.name = info.title if info.language_id == 1
end

EDIT

In my Rails app contents can be inserted in many languages, but are displayed only in one of them. Other languages are used only as XML output. However the main cause i'm using this approach is that without a "name" attribute i wouldn't be able to create a collection like this:

<%= collection_select(:event, :activity_id, @activities, :id, :name) %>

Can you suggest me how to accomplish this without a "name" attribute in my Activity?

开发者_JAVA技巧Thanks!


You can do something like this.

info = @activity.infos.select{|info| info.language_id == 1}.last
@activity.name = info.title


Same as the others but using the ARrel syntax that's available in rails 3.

@activity.name = @activity.infos.where(:language_id => 1).first.title

As the others mentioned ... you might want rethink your design. If you provide more detail on why you are trying to do this we may be able to help with the underlying design that lead to this.


Well, you could lose the iteration...

@activity.name = @activity.infos.find(:first, :conditions => { :language_id => 1 }).title

but that doesn't guarantee you'll get a result (in the real world). So:

info = @activity.infos.find(:first, :conditions => { :language_id => 1 })
@activity.name = info.title unless info.nil?

But as mentioned in the comments this is a strange approach - seems like there's something structurally wrong with your app/data if you're trying to assign a value this way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜